LeetCode Blind 75 in Swift: Solving the "Best Time to Buy and Sell Stock" Problem
LeetCode Blind 75 in Swift: Solving the "Best Time to Buy and Sell Stock" Problem
Problem: Best Time to Buy and Sell Stock
The Best Time to Buy and Sell Stock problem asks for the maximum profit you can achieve from buying and selling a stock.
Given an array where prices[i] represents the price of a given stock on day i, find the maximum profit you can achieve. You may not engage in multiple transactions (you must sell the stock before you buy again).
Example:
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.
Swift Solution
class Solution {
func maxProfit(_ prices: [Int]) -> Int {
var minPrice = Int.max
var maxProfit = 0
for price in prices {
if price < minPrice {
minPrice = price
} else if price - minPrice > maxProfit {
maxProfit = price - minPrice
}
}
return maxProfit
}
}
let solution = Solution()
let prices = [7, 1, 5, 3, 6, 4]
let result = solution.maxProfit(prices)
print(result) // Output: 5
Explanation
This approach involves scanning through the prices array while keeping track of the minimum price seen so far and the maximum profit possible. On each day, we calculate the potential profit if we were to sell at the current price and compare it with the highest recorded profit.
Comments
Post a Comment