Best Time to Buy and Sell Stock II

Say you have an array for which the $i^{th}$ 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 天的股票价格。现要求设计一个算法,使得获得的盈利最大。买进股票后,必须卖出,才能继续买进

分析

要想利润最大,即最低时买进,最高时卖出

$$Total\,Profit = \sum_{i}(height(peak_i)-height(valley_i))$$

具体观察可发现,峰值减去谷值,也就是递增段的和,如 A + B + C = D

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
public int maxProfit(int[] prices) {

int sum = 0, n = prices.length, k;

for (int i = 1; i < n; i++) {

k = prices[i] - prices[i - 1];

if (k > 0) {
sum += k;
}
}

return sum;
}
}