@@ -47,26 +47,28 @@ public static int maxProfit(int[] prices) {
4747
4848 return max ;
4949 }
50-
50+
51+ // O(N) Time | O(1) Space
5152 public static int maxProfit3 (int [] prices ) {
5253
53- int minVal = Integer .MAX_VALUE ;
54+ int minBuyPrice = Integer .MAX_VALUE ;
5455 int maxProfit = 0 ;
5556
56- for (int i = 0 ; i < prices .length ; i ++) {
57- if (prices [i ] < minVal ) {
58- minVal = prices [i ];
59- } else if (prices [i ] - minVal > maxProfit ) {
60- maxProfit = prices [i ] - minVal ;
57+ for (int currentPrice : prices ) {
58+
59+ if (currentPrice < minBuyPrice ) {
60+ minBuyPrice = currentPrice ;
61+
62+ } else if (currentPrice - minBuyPrice > maxProfit ) {
63+ maxProfit = currentPrice - minBuyPrice ;
6164 }
6265 }
63-
6466 return maxProfit ;
6567 }
6668
6769 public static void main (String [] args ) {
68- int [] prices = { 7 , 1 , 5 , 3 , 6 , 4 };
69- // int[] prices = { 7, 6, 4, 3, 1 };
70+ // int[] prices = { 7, 1, 5, 3, 6, 4 };
71+ int [] prices = { 7 , 6 , 4 , 3 , 1 };
7072 System .out .println (maxProfit3 (prices ));
7173 }
7274}
0 commit comments