- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem122.java
More file actions
Latest commit
30 lines (28 loc) · 856 Bytes
/
Copy pathProblem122.java
File metadata and controls
30 lines (28 loc) · 856 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
classProblem122 {
publicstaticvoidmain(String[] args) {
int[] prices = {7,1,5,3,6,4};
intres = newProblem122().maxProfit(prices);
System.out.println(res);
}
publicintmaxProfit(int[] prices) {
intbuy_pos = 0;
intsale_pos = 0;
intprofit = 0;
for (inti = 1; i < prices.length; i++) {
if (prices[i] >= prices[sale_pos]) {
//递增趋势
sale_pos = i;
} else { //递减趋势
if (sale_pos > buy_pos) {
profit += (prices[sale_pos] - prices[buy_pos]);
}
buy_pos = i;
sale_pos = i;
}
}
if (sale_pos > buy_pos) {
profit += (prices[sale_pos] - prices[buy_pos]);
}
returnprofit;
}
}