您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:Best Time to Buy and Sell Stock II(122)

2016-06-10 23:19 525 查看

题目

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个数表示股票在第i天的价格。交易次数不限,但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。

分析:贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格,就算入收益。

代码:时间O(n),空间O(1)。

此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。

class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<2)
return 0;
int maxprofile=0;
for(int i=1;i<prices.size();i++){
int diff=prices[i]-prices[i-1];
if(diff>0)
maxprofile+=diff;

}
return maxprofile;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: