"
✅ Passes all test cases:
Tricky:
stock_prices = [1, 10, 2, 3]
output: 9 (Buy on day 1 at 1 and sell on day 2 at 10)
func maxProfit(_ stockPrices: [Int]) -> Int {
var options: [Int] = [] // min-heap
var currentProfit = 0
var maxProfit = 0
for price in stockPrices {
if let cheapestOption = options.last, cheapestOption < price {
if currentProfit < price {
currentProfit += price // greedy profit
} else {
"
Reno S. - "
✅ Passes all test cases:
Tricky:
stock_prices = [1, 10, 2, 3]
output: 9 (Buy on day 1 at 1 and sell on day 2 at 10)
func maxProfit(_ stockPrices: [Int]) -> Int {
var options: [Int] = [] // min-heap
var currentProfit = 0
var maxProfit = 0
for price in stockPrices {
if let cheapestOption = options.last, cheapestOption < price {
if currentProfit < price {
currentProfit += price // greedy profit
} else {
"See full answer
"
O(n) time, O(1) space
from typing import List
def maxsubarraysum(nums: List[int]) -> int:
if len(nums) == 0:
return 0
maxsum = currsum = nums[0]
for i in range(1, len(nums)):
currsum = max(currsum + nums[i], nums[i])
maxsum = max(currsum, max_sum)
return max_sum
debug your code below
print(maxsubarraysum([-1, 2, -3, 4]))
`"
Rick E. - "
O(n) time, O(1) space
from typing import List
def maxsubarraysum(nums: List[int]) -> int:
if len(nums) == 0:
return 0
maxsum = currsum = nums[0]
for i in range(1, len(nums)):
currsum = max(currsum + nums[i], nums[i])
maxsum = max(currsum, max_sum)
return max_sum
debug your code below
print(maxsubarraysum([-1, 2, -3, 4]))
`"See full answer
"from typing import List
def traprainwater(height: List[int]) -> int:
if not height:
return 0
l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0
while l < r:
if leftMax < rightMax:
l += 1
leftMax = max(leftMax, height[l])
res += leftMax - height[l]
else:
r -= 1
rightMax = max(rightMax, height[r])
"
Anonymous Roadrunner - "from typing import List
def traprainwater(height: List[int]) -> int:
if not height:
return 0
l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0
while l < r:
if leftMax < rightMax:
l += 1
leftMax = max(leftMax, height[l])
res += leftMax - height[l]
else:
r -= 1
rightMax = max(rightMax, height[r])
"See full answer
Software Engineer
Data Structures & Algorithms
+4 more
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.