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

解题:

将数组中每一个值都想象成数轴上的一个点,只要当前点比前一个点上升了,则此段收益就能够通过买入卖出获得;(即使是连续上升,可以中间段不卖出,收益也全都获得,因此不影响计算策略)。

代码:

 class Solution {
public:
int maxProfit(vector<int> &prices) {
int size = prices.size();
int maxP = ;
for (int i = ; i < size; ++i) {
if (prices[i] > prices[i-])
maxP += prices[i] - prices[i-];
}
return maxP;
}
};
04-14 14:09