-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ122.java
More file actions
30 lines (29 loc) · 784 Bytes
/
Q122.java
File metadata and controls
30 lines (29 loc) · 784 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
/*
* @Author: Shawn Yang
* @Date: 2019-09-06 08:00:43
* @Last Modified by: Shawn Yang
* @Last Modified time: 2019-09-06 10:20:21
*/
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) {
return 0;
}
int valley = prices[0];
int peak = prices[0];
int result = 0;
int i = 0;
while(i < prices.length - 1) {
while(i < prices.length - 1 && prices[i] >= prices[i + 1]) {
i++;
}
valley = prices[i];
while(i < prices.length -1 && prices[i] <= prices[i + 1]) {
i++;
}
peak = prices[i];
result += peak - valley;
}
return result;
}
}