LeetCode(122)Best Time to Buy and Sell Stock2

来源:互联网 发布:正义不会缺席知乎 编辑:程序博客网 时间:2024/05/27 09:45

题目如下:

Say you have an array for which the ith element is the price of a given stock on day i.
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).


分析如下:

有了前一道题目的基础,我不止一次地被坑了。。。

首先想,把上一道题目的结论作为基础,然后不断递归就行了。首先求出第一次交易的买入价i卖出价j,然后在没有交易的时间段中,递归求解买入价和卖出价,不断进行,直到所有的时间段都被试探过了为止。递归的解法提交时说memory limit exceeded.

然后想,那就说明递归开销太大了,于是把其中每次复制vector的那段改了改,省去了复制vector的开销,提交,说time limit exceeded。

实在不知道该怎么改啊。于是看了官网讨论上的答案了,跪。

//官网答案class Solution {public:    int maxProfit(vector<int> &prices) {        int p = 0;        for(int i = 1; i < prices.size() ; ++i) {            int delta = prices[i] - prices[i-1];            if(delta > 0 ) {                p += delta;            }        }        return p;    }};

如果能够跳出局部,从整理看问题,这道题就非常容易了。

N天的总利润如何最大呢?就是一旦有获利空间就去赚钱,所以就是把每两天的价格增长量加起来就是总利润了,如果存在两天的价格增长量为负,那么就不进行交易。

所以,这道题目其实是个数学问题,考察是否有化零为整的思路。也突然觉得leetcode的online judge很有意思,不知道他们是如何设定的可以使得这道题目只有提交最优化的算法才能通过online judge. 一个可行的办法是,做比较轻松的设定,设定运行时间的数量级而不是具体数值。


小结提高:

1. stock问题有4个系列,分别在 1, 2, 3, 4。

0 0