Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
func maxProduct(_ nums: [Int]) -> Int { if nums.isEmpty { return 0 } var gm = nums[0], lmax = nums[0], lmin = nums[0], i = 1 while i < nums.count { let t = [lmax * nums[i], nums[i], lmin * nums[i]] lmin = t.min()! lmax = t.max()! gm = max(lmax, gm) i += 1 } return gm } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼