Skip to content

Commit b4e74e7

Browse files
author
Yi Gu
committed
[Array] Add a solution to Best Time Buy Sell Stock II
1 parent 599d991 commit b4e74e7

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Array/BestTimeBuySellStockII.swift

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
3+
* Primary idea: Add all substractions if sell stock could earn money
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*
6+
*/
7+
8+
class BestTimeBuySellStockII {
9+
func maxProfit(_ prices: [Int]) -> Int {
10+
var max = 0
11+
12+
guard prices.count > 1 else {
13+
return max
14+
}
15+
16+
for i in 1 ..< prices.count {
17+
if prices[i] > prices[i - 1] {
18+
max += prices[i] - prices[i - 1]
19+
}
20+
}
21+
22+
return max
23+
}
24+
}

0 commit comments

Comments
 (0)