⚡ TL;DR
Solve Best Time to Buy and Sell Stock in Swift with working code. One-Pass Min Tracking (Optimal) approach with O(n) time, plus complexity analysis and interview tips.
Best Time to Buy and Sell Stock (#121 — Easy): Given an array prices where prices[i] is the price of a stock on day i, choose one day to buy and a different later day to sell to maximize profit. Return that maximum profit, or 0 when no profitable trade exists.
Problem Statement
Given an array prices where prices[i] is the price of a stock on day i, choose one day to buy and a different later day to sell to maximize profit. Return that maximum profit, or 0 when no profitable trade exists.
Example:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1), sell on day 5 (price = 6), profit = 6 − 1 = 5.Approach: One-Pass Min Tracking (Optimal)
Time: O(n) | Space: O(1)
Walk the prices once while remembering the cheapest price seen so far. At each day the best possible trade selling today is today’s price minus that minimum, so update the answer on the fly.
func maxProfit(_ prices: [Int]) -> Int {
var minPrice = prices[0]
var best = 0
for price in prices.dropFirst() {
if price < minPrice {
minPrice = price
} else if price - minPrice > best {
best = price - minPrice
}
}
return best
}
print(maxProfit([7, 1, 5, 3, 6, 4]))Approach: Brute Force
Time: O(n²) | Space: O(1)
Try every buy-day/sell-day pair, keep the largest positive difference, and return it. Straightforward but quadratic, which fails on large inputs.
func maxProfitBrute(_ prices: [Int]) -> Int {
var best = 0
for i in 0..<prices.count {
for j in (i + 1)..<prices.count {
if prices[j] - prices[i] > best { best = prices[j] - prices[i] }
}
}
return best
}
print(maxProfitBrute([7, 1, 5, 3, 6, 4]))Key Takeaways
- Start with the brute-force approach to understand the problem
- One-Pass Min Tracking (Optimal) gives the optimal O(n) solution
- Practice this pattern — it appears frequently in coding interviews
FAQ
What is the best approach to solve Best Time to Buy and Sell Stock in Swift?
The recommended approach is One-Pass Min Tracking (Optimal), which runs in O(n) time with O(1) space. The full Swift implementation is shown above.
What is the time complexity of Best Time to Buy and Sell Stock in Swift?
Using One-Pass Min Tracking (Optimal), the time complexity is O(n) and the space complexity is O(1).
Happy coding!
