-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution122.java
More file actions
32 lines (29 loc) · 932 Bytes
/
Solution122.java
File metadata and controls
32 lines (29 loc) · 932 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 买卖股票的最佳时机 II
* @date: 2018/08/19
*/
public class Solution122 {
/**
* 由于可以多次买卖股票:
* 对于 [a, b, c, d],如果有 a <= b <= c <= d ,那么最大收益为 d - a。
* 而 d - a = (d - c) + (c - b) + (b - a) ,因此当访问到一个 prices[i] 且 prices[i] - prices[i-1] > 0,
* 那么就把 prices[i] - prices[i-1] 添加到收益中,从而在局部最优的情况下也保证全局最优。
*
* @param prices
* @return
*/
public int maxProfit(int[] prices) {
if (null == prices || 0 >= prices.length) {
return 0;
}
int profit = 0;
for (int i = 1; i < prices.length; ++i) {
if (prices[i - 1] < prices[i]) {
profit += (prices[i] - prices[i - 1]);
}
}
return profit;
}
}