@@ -16,6 +16,35 @@ public static int maxProfit(int[] prices) {
1616 return total ;
1717 }
1818
19+ // another approach to keep track of buy and selling date
20+ public static int maxProfit2 (int [] prices ) {
21+ if (prices .length < 2 )
22+ return 0 ;
23+
24+ int profit = 0 ;
25+ int buyDate = 0 , sellDate = 0 ;
26+
27+ for (int i = 1 ; i < prices .length ; i ++) {
28+ if (prices [i ] >= prices [i - 1 ]) {
29+ // if stock price is increasing, we can sell current hold of
30+ // stock in future with higher price
31+ sellDate ++;
32+ } else {
33+ // if stock graph starts to decrease, sell the previously hold
34+ // stock
35+ profit += (prices [sellDate ] - prices [buyDate ]);
36+ // now set new buy and sell date to current date after
37+ // collecting previous profits
38+ buyDate = sellDate = i ;
39+ }
40+ }
41+
42+ // now collecting profit from final increase in stock prices (final dip)
43+ profit += (prices [sellDate ] - prices [buyDate ]);
44+
45+ return profit ;
46+ }
47+
1948 public static void main (String [] args ) {
2049
2150 int [] prices = { 7 , 1 , 5 , 3 , 6 , 4 };
@@ -24,5 +53,12 @@ public static void main(String[] args) {
2453 System .out .println (maxProfit (new int [] { 1 , 2 , 3 , 4 , 5 }));
2554 System .out .println (maxProfit (new int [] { 7 , 6 , 4 , 3 , 1 }));
2655
56+ // testing another approach
57+ System .out .println ();
58+ System .out .println (maxProfit2 (prices ));
59+
60+ System .out .println (maxProfit2 (new int [] { 1 , 2 , 3 , 4 , 5 }));
61+ System .out .println (maxProfit2 (new int [] { 7 , 6 , 4 , 3 , 1 }));
62+
2763 }
2864}
0 commit comments