Skip to content

Commit 62952cb

Browse files
author
Jeongwon Na
committed
best time to buy and sell stock solution
1 parent bd68fd6 commit 62952cb

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Time Complexity: O(n), n: prices.length
2+
// Space Complexity: O(1), because 3 int-variables are declared -> O(1)+O(1)+O(1)
3+
class Solution {
4+
public int maxProfit(int[] prices) {
5+
int buyPrice = prices[0];
6+
int sellPrice = 0;
7+
int profit = 0; // store maxProfit
8+
9+
for (int i = 1; i < prices.length; ++i) {
10+
buyPrice = Math.min(buyPrice, prices[i]);
11+
profit = Math.max(profit, prices[i] - buyPrice);
12+
}
13+
14+
return profit;
15+
}
16+
}

0 commit comments

Comments
 (0)