Skip to content

Commit 2f1f51a

Browse files
solve sbest time to buy and sell stock II
1 parent 725a346 commit 2f1f51a

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/BestTimeToBuyAndSellStockII.java

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class BestTimeToBuyAndSellStockII {
2+
public int maxProfit(int[] prices) {
3+
if (prices.length == 0) {
4+
return 0;
5+
}
6+
7+
int sellPrice = prices[0];
8+
int buyPrice = prices[0];
9+
int profit = 0;
10+
11+
for (int index = 1 ; index <prices.length ; index++) {
12+
if (prices[index] < sellPrice) {
13+
profit += sellPrice - buyPrice;
14+
sellPrice = buyPrice = prices[index];
15+
} else {
16+
sellPrice = prices[index];
17+
}
18+
}
19+
profit += sellPrice - buyPrice;
20+
21+
return profit;
22+
}
23+
}

0 commit comments

Comments
 (0)