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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
作为上一道题的延续,本来想把之前找最小值最大差的方法写一个递归,结果发现自己理不清思路。
于是参考了网上的资料,发现一种巧妙的差值求解方法。
参考博客地址:http://www.cnblogs.com/TenosDoIt/p/3436457.html
对于前一道题:按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2]。求新数组的最大子段和就是我们求得最大利润,假设最大子段和是从新数组第 i 到第 j 项,那么子段和= prices[j]-prices[j-1]+prices[j-1]-prices[j-2]+...+prices[i]-prices[i-1] = prices[j]-prices[i-1], 即prices[j]是最大价格,prices[i-1]是最小价格,且他们满足前后顺序关系。代码如下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
int len = prices.size();
if(len <= 1)return 0;
int res = 0, currsum = 0;
for(int i = 1; i < len; i++)
{
if(currsum <= 0)
currsum = prices[i] - prices[i-1];
else
currsum += prices[i] - prices[i-1];
if(currsum > res)
res = currsum;
}
return res;
}
};
然后这一道题的话,还是首先建立差值数组,再求出所有正数的和。
同上一题构建股票差价数组,把数组中所有差价为正的值加起来就是最大利润了。其实这和算法1差不多,因为只有递增区间内的差价是正数,并且同一递增区间内所有差价之和 = 区间最大价格 - 区间最小价格。代码如下:
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 0; i < prices.length - 1; ++i) {
if (prices[i] < prices[i + 1]) {
res += prices[i + 1] - prices[i];
}
}
return res;
}
}
感觉这两道题的算法都比较巧妙,可以记住一下。