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).
[Anylysis]
相当于在一个数组中,找出所有的递增子序列(要求每个子序列内的元素在原数组中连续),计算这些递增子序列的递增和。
例如:1,3,5,2,4,6,4,5,7中,存在三个递增子序列[1,3,5][2,4,6][4,5,7],它们的递增和分别是(5-1)=4,(6-2)=4,(7-4)=3,所以总和是4+4+3=11,也就是本题中的maximum profit。
在本题中,只需要对所有元素进行一次遍历就可以找出所有的连续递增子序列,复杂度为O(n)
[Solution]
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.size() <= 0)return 0;
// add all increasing sub-sequence
int min = prices[0], max = prices[0], sum = 0;
for(int i = 1; i < prices.size(); ++i){
if(prices[i] >= prices[i-1]){
max = prices[i];
}
else{
sum += (max - min);
max = min = prices[i];
}
}
// be careful to add the last increasing sub-sequence
sum += (max - min);
return sum;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客