-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxProfit.java
More file actions
29 lines (25 loc) · 869 Bytes
/
MaxProfit.java
File metadata and controls
29 lines (25 loc) · 869 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
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
public class MaxProfit {
public int maxProfit(int[] prices) {
int i = 0;
int valley = prices[0];
int peak = prices[0];
int maxprofit = 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];
maxprofit += peak - valley;
}
return maxprofit;
}
public static void main(String[] args) {
}
}