Best Time to Buy and Sell Stock II

来源:互联网 发布:逛淘宝流量消耗异常 编辑:程序博客网 时间:2024/06/03 17:37

https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/


Say you have an array for which the ith element is the price of a given stock on dayi.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

public int maxProfit(int[] prices)


这题可以解读为把所有的极大点都和当前的距离最近的极小点相减,然后差的和就是答案了。但其实,代码逻辑上可以很简单很简单的。。简单来说当前元素比之前那个元素大你就减,就可以了。。。我举个例子, 3,5,9,1,6,10。 在这个数组上,极大点有两个,9 和10, 它们所对应的极小点有两个,3 和1。 但实际上, 9 - 5 + 5 - 3和 9 - 3是一样的... 10 - 6 + 6 - 1和 10 - 1 也是一样的。所以只要把能减的都减了,最后自然就会形成极大点减去极小点的效果....


    public int maxProfit(int[] prices) {        int profit = 0;        for(int i = 1; i < prices.length; i++){            if(prices[i] > prices[i - 1])                profit += prices[i] - prices[i - 1];        }        return profit;    }


0 0