forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_122.java
36 lines (34 loc) · 1.07 KB
/
_122.java
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
34
35
36
package com.fishercoder.solutions;
public class _122 {
public static class Solution1 {
//peak and valley approach
public int maxProfit(int[] prices) {
int pro = 0;
int i = 0;
while (i < prices.length - 1) {
while (i < prices.length - 1 && prices[i] >= prices[i + 1]) {
i++;
}
int valley = prices[i];
while (i < prices.length - 1 && prices[i] <= prices[i + 1]) {
i++;
}
int peak = prices[i];
pro += peak - valley;
}
return pro;
}
}
public static class Solution2 {
//simple one pass approach: the above solution could be simplied as below
public int maxProfit(int[] prices) {
int pro = 0;
for (int i = 0; i < prices.length - 1; i++) {
if (prices[i + 1] > prices[i]) {
pro += prices[i + 1] - prices[i];
}
}
return pro;
}
}
}