Skip to content

Commit bb39f57

Browse files
author
Li Li
committed
add code of 122
1 parent 3d3127d commit bb39f57

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// find each nearby peak , valley
2+
public class Solution {
3+
public int MaxProfit(int[] prices) {
4+
if (prices == null || prices.Length < 2) {
5+
return 0;
6+
}
7+
int i = 0;
8+
int valley = prices[0];
9+
int peak = prices[0];
10+
int maxProfit = 0;
11+
while (i < prices.Length - 1) {
12+
// find valley
13+
while (i < prices.Length - 1 && prices[i] >= prices[i + 1]){
14+
i++;
15+
}
16+
valley = prices[i];
17+
// find peak
18+
while (i < prices.Length - 1 && prices[i] <= prices[i + 1]) {
19+
i++;
20+
}
21+
peak = prices[i];
22+
maxProfit += peak - valley;
23+
}
24+
return maxProfit;
25+
}
26+
}
27+
28+
// if shape a ->b->c->d keep increasing, a as valley, d is peak,
29+
// d - a = d- c + c - b + b -a;
30+
// so we don't need find exact peak d, just use d-c, c -b, b -a. then Sum.
31+
public class Solution {
32+
public int MaxProfit(int[] prices) {
33+
if (prices == null || prices.Length < 2) {
34+
return 0;
35+
}
36+
int maxProfit = 0;
37+
for (int i = 1; i < prices.Length; i++) {
38+
if (prices[i] > prices[i - 1]) {
39+
maxProfit += prices[i] - prices[i - 1];
40+
}
41+
}
42+
return maxProfit;
43+
}
44+
}

0 commit comments

Comments
 (0)