forked from mr-robot-2008/html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBest_Time_to_Buy_and_Sell_Stock.java
49 lines (31 loc) · 1.2 KB
/
Best_Time_to_Buy_and_Sell_Stock.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
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public int maxProfit(int[] prices) {
//Brute Force : --> Time Limit Exceeding
// int profit = Integer.MIN_VALUE;
// for (int i=0;i<prices.length;i++){
// for(int j=i+1;j<prices.length;j++){
// if ((prices[j]-prices[i])>profit)
// profit=prices[j]-prices[i];
// }
// }
// if (profit<0) return 0;
// return profit;
//One -Pointer Appraoch + O(n)
// int buy = Integer.MAX_VALUE;
// int profit = 0;
// for(int i=0; i < prices.length; i++){
// if(prices[i] < buy) buy = prices[i];
// profit = Math.max(profit, prices[i] - buy); //sell = prices[i] - buy;
// }
// return profit;
//Approach 02
int buy =Integer.MAX_VALUE, max=0;
for (int i=0;i<prices.length;i++){
if(buy>prices[i]) buy = prices[i];
max= Math.max(max, prices[i]-buy);
}
return max;
}
}
// Input: prices = [7,1,5,3,6,4]
// Output: 5