Swift DSA: Best Time to Buy and Sell Stock - COFPROG

Swift DSA: Best Time to Buy and Sell Stock

Swift: Best Time to Buy and Sell Stock

Problem: Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction.

Examples:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No transactions are done as prices only decrease.

Swift Solution

class Solution {
    func maxProfit(_ prices: [Int]) -> Int {
        guard prices.count > 1 else { return 0 }
        
        var minPrice = Int.max
        var maxProfit = 0
        
        for price in prices {
            // Update minimum price seen so far
            minPrice = min(minPrice, price)
            
            // Calculate potential profit if we sell at current price
            let potentialProfit = price - minPrice
            
            // Update maximum profit if current potential profit is greater
            maxProfit = max(maxProfit, potentialProfit)
        }
        
        return maxProfit
    }
}

// Example usage
let solution = Solution()

// Test Case 1
let prices1 = [7,1,5,3,6,4]
print(solution.maxProfit(prices1))  // Output: 5

// Test Case 2
let prices2 = [7,6,4,3,1]
print(solution.maxProfit(prices2))  // Output: 0

// Test Case 3
let prices3 = [2,4,1,7]
print(solution.maxProfit(prices3))  // Output: 6

Explanation

This solution uses Kadane's algorithm principle with some modifications. Here's how it works:

1. We initialize two variables:

- minPrice: tracks the minimum price seen so far

- maxProfit: tracks the maximum profit possible

2. For each price in the array:

- Update minPrice if current price is lower

- Calculate potential profit if we sell at current price

- Update maxProfit if current potential profit is higher

Time Complexity: O(n) where n is the length of the prices array

Space Complexity: O(1) as we only use two variables

Key Insights:

- We only need to make one pass through the array

- At each step, we're asking: "If I sell today, what's my profit?"

- We keep track of the minimum price seen so far to calculate potential profit

- This approach works because we only need to find one buy and one sell point

Previous
Next Post »

BOOK OF THE DAY