FTPrep, 122 Best Time to Buy and Sell Stock II

来源:互联网 发布:网络消费安全的ppt 编辑:程序博客网 时间:2024/06/06 02:28

思路和121 是一样的,这里的变化是可以多次交易。所以只要遇到比当前价格低的股价时,就立马交易,然后买入这个低股价,同时跟新low,high,当前次的profit

这个也是优化过的结果,而不是用local + global哪种模版套用。但是在下一题模版会比较有用,因为很难优化,条件比较复杂,是动态的,比如说是K次。121-123这三道题连贯性不错,从个例出发,慢慢到generalized form。这符合我总结题目的思路。

代码如下:

class Solution {    public int maxProfit(int[] prices) {        int len= prices.length;        if(len==0) return 0;        int lowPrice=prices[0];        int highPrice=prices[0];        int profit=0;        int totalProfit=0;        for(int day=0; day<len; day++){            if(prices[day]>highPrice){                highPrice=prices[day];                profit=highPrice-lowPrice;            }            else if(prices[day]<highPrice){                totalProfit+=profit;                profit=0;                lowPrice=prices[day];                highPrice=prices[day];                            }        }        totalProfit+=profit; // the last transaction has to be added as well.        return totalProfit;    }}// 和上一题一样的思路,只需要多一个totalProfit 把每次的profit都加起来就可以,什么时候加?在遇到新的lowPrice之前。// 以上的思路是有偏差的,为什么?因为如果出现 【1,6, 2, 8】,最大交易是两次的加和:(6-1)+(8-2)=13; 而不是单次的最大单词交易额(8-1)。// 买股票的题型这两道很有关联,单词交易最大profit,和多次交易最大收益。上面的1628的例子就是个最典型的例子说明两者的差别。zigzag shape