-
Notifications
You must be signed in to change notification settings - Fork 153
/
MaxProfit.java
31 lines (26 loc) · 927 Bytes
/
MaxProfit.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
package MaxProfit;
class Solution {
public int solution(int[] A) {
// main idea (One Pass Solution):
// We can maintain two variables
// 1) minprice (key point~!!)
// 2) maxprofit (corresponding to the smallest valley)
// special case
if(A.length <= 1)
return 0; // no profit
// two variables (and initial setting)
int minPrice = A[0];
int maxProfit =0;
// one pass solution
for(int i=1; i<A.length; i++){
if(A[i] < minPrice) // case 1: from high to low
minPrice = A[i];
else{ // case 2: from low to high
int curProfit = A[i] - minPrice;
if(curProfit > maxProfit) // update max profit
maxProfit = curProfit;
}
}
return maxProfit;
}
}