iOS Interview - Leetcode 121. Best Time to Buy and Sell Stock

May 03, 20241 min read#swift, #interview, #leetcode

Leetcode: 121. Best Time to Buy and Sell Stock

  • Primary idea: Dynamic programming, iterate through the prices and update the minimum price and maximum profit accordingly
  • Time Complexity: O(n)
  • Space Complexity: O(1)
 func maxProfit(_ prices: [Int]) -> Int {
    var minPrice = Int.max
    var maxProfit = 0

    for price in prices {
        // Find the minimum stock price
        minPrice = min(price, minPrice)

        // Continuously update the max profit based on the new minimum price.
        maxProfit = max(maxProfit, price - minPrice)
    }

    return maxProfit
}

print(maxProfit([7,1,5,3,6,4])) // 5
print(maxProfit([7,6,4,3,1])) // 0
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024