122. Best Time to Buy and Sell Stock II

来源:互联网 发布:同城团购用什么软件 编辑:程序博客网 时间:2024/05/15 13:10

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

题意:可以多次buy和sell,要求buy和sell区间不能重叠,求最大收益。

思路:画出股票价格的折线图,则全局最大和,即为各段上升区间的和。也是每天所能得到的收益和,即:如果今天股票涨价,则今天得到部分收益,如果后天继续增,后天继续得到收益,某天降价了,则这个阶段的累积收益完毕,从下一个阶段开始计算累积收益,这样就能得出股票的最大和。

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




0 0
原创粉丝点击