您的位置:首页 > 其它

LeetCode(122) Best Time to Buy and Sell Stock II

2015-10-30 16:22 381 查看

题目

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).

Subscribe to see which companies asked this question

分析

买卖股票II,与 LeetCode(121) Best Time to Buy and Sell Stock的区别就是,此次允许买卖多次,但是必须卖出后才可下次买入。

实际上是求股价波浪线的所有上升段的长度和。

AC代码

class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty())
return 0;

int sum = 0;
//只要后项比前项大,这部分值就一定可以变为利润
for (size_t i = 1; i < prices.size(); ++i)
{
if (prices[i] > prices[i - 1])
sum += (prices[i] - prices[i - 1]);
}
return sum;
}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: