Skip to content

Commit 9934165

Browse files
authored
Create 121. Best Time to Buy and Sell Stock.java
1 parent 9a5e25f commit 9934165

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock
2+
3+
public class Solution {
4+
public int maxProfit(int[] prices) {
5+
if (prices.length <= 1) return 0;
6+
7+
int maxProfit = 0;
8+
int minPrice = prices[0];
9+
10+
for (int i = 1; i < prices.length; i++) {
11+
if (prices[i] < minPrice) {
12+
minPrice = prices[i];
13+
}
14+
if (prices[i] - minPrice > maxProfit) {
15+
maxProfit = prices[i] - minPrice;
16+
}
17+
}
18+
19+
return maxProfit;
20+
}
21+
}

0 commit comments

Comments
 (0)