LeetCode Blind 75 in Swift: Solving the "Maximum Product Subarray" Problem
Problem: Maximum Product Subarray
The Maximum Product Subarray problem asks you to find the contiguous subarray within an array (containing at least one number) that has the largest product.
Example:
Input: nums = [2, 3, -2, 4]
Output: 6
Explanation: [2, 3] has the largest product = 6.
Swift Solution
class Solution {
func maxProduct(_ nums: [Int]) -> Int {
var currentMax = nums[0]
var currentMin = nums[0]
var result = nums[0]
for num in nums.dropFirst() {
let tempMax = currentMax
currentMax = max(num, currentMax * num, currentMin * num)
currentMin = min(num, tempMax * num, currentMin * num)
result = max(result, currentMax)
}
return result
}
}
let solution = Solution()
let nums = [2, 3, -2, 4]
let result = solution.maxProduct(nums)
print(result) // Output: 6
Explanation
In this solution, we maintain two values: the maximum product and the minimum product at each point in the array. This is because a negative number can turn a minimum product into a maximum when multiplied. As we traverse the array, we calculate the maximum and minimum products at each step and update the result accordingly.
Comments
Post a Comment