Skip to content

Commit 195d6ea

Browse files
committed
LC#121 revised-best time to buy & sell stock problem, O(N) time O(1) space
1 parent 7a17b6e commit 195d6ea

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package practice.revisited;
2+
3+
/*
4+
Input: prices = [7,1,5,3,6,4]
5+
Output: 5
6+
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
7+
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
8+
*/
9+
10+
public class BestTimeToBuyAndSellStock121 {
11+
12+
public static int maxProfit(int[] prices) {
13+
if (prices.length < 2)
14+
return 0;
15+
int profit = 0;
16+
int currlow = prices[0];
17+
int sell = 0;
18+
19+
for (int curr = 1; curr < prices.length; curr++) {
20+
21+
if (prices[curr] < currlow) {
22+
currlow = prices[curr];
23+
}
24+
sell = prices[curr] - currlow;
25+
profit = Math.max(profit, sell);
26+
}
27+
return profit;
28+
}
29+
30+
public static void main(String[] args) {
31+
int[] prices = { 7, 1, 5, 3, 6, 4 };
32+
System.out.println(maxProfit(prices));
33+
System.out.println(maxProfit(new int[] { 7, 6, 4, 3, 1 }));
34+
}
35+
}

0 commit comments

Comments
 (0)