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
33 | public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;
int[] profit = new int[prices.length];
int[] profit_r = new int[prices.length];
findMaxI(prices, profit);
findMaxII(prices, profit_r);
int max = 0;
for (int i = 0; i < prices.length; i++){
max = Math.max(profit[i]+profit_r[i], max);
}
return max;
}
private void findMaxII(int[]prices, int profit[]){
int currentMax = prices[prices.length-1];
int last = profit[prices.length-1];
for (int i = prices.length-2; i >= 0; i--){
profit[i] += Math.max(profit[i+1], currentMax-prices[i]);
currentMax = Math.max(prices[i], currentMax);
}
return;
}
private void findMaxI(int[]prices, int profit[]){
int currentMin = prices[0];
for (int i = 1; i < prices.length; i++){
profit[i] = Math.max(profit[i-1], prices[i]-currentMin);
currentMin = Math.min(prices[i], currentMin);
}
return;
}
}
|
No comments:
Post a Comment