33public class BestTimeToBuyAndSellStock121 {
44
55 // O(N^2) Time | O(1) Space
6- public static int maxProfit (int [] prices ) {
6+ public static int maxProfit1 (int [] prices ) {
77
88 int max = 0 ;
99
@@ -22,9 +22,40 @@ public static int maxProfit(int[] prices) {
2222 return max ;
2323 }
2424
25+ // using Kadance's algorithm
26+ // O(N) Time | O(1) Space
27+ public static int maxProfit (int [] prices ) {
28+
29+ if (prices .length < 2 )
30+ return 0 ;
31+
32+ int max = 0 ;
33+ int currentMax = 0 ;
34+
35+ for (int i = 1 ; i < prices .length ; i ++) {
36+
37+ currentMax = currentMax + (prices [i ] - prices [i - 1 ]);
38+
39+ if (currentMax > max ) {
40+ max = currentMax ;
41+ }
42+
43+ if (currentMax < 0 ) {
44+ currentMax = 0 ;
45+ }
46+ }
47+
48+ return max ;
49+ }
50+
2551 public static void main (String [] args ) {
26- // int[] prices = { 7, 1, 5, 3, 6, 4 };
27- int [] prices = { 7 , 6 , 4 , 3 , 1 };
52+ int [] prices = { 7 , 1 , 5 , 3 , 6 , 4 };
53+ // int[] prices = { 7, 6, 4, 3, 1 };
2854 System .out .println (maxProfit (prices ));
2955 }
3056}
57+
58+ // for (int i = 1; i < prices.length; i++) {
59+ // currentMax = Math.max(0, currentMax + prices[i] - prices[i - 1]);
60+ // max = Math.max(max, currentMax);
61+ // }
0 commit comments