标签:example number nta res inpu not ann int col
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
题意:
求最大乘积子数组
思路:
负负得正,正负得负。
/ 最大乘积子数组 * nums[i]
所以nums[i] 结尾的最大乘积子数组取决于nums[i-1]结尾的
\ 最小乘积子数组 * nums[i]
代码:
1 class Solution { 2 public int maxProduct(int[] nums) { 3 int[] max = new int[nums.length]; 4 int[] min = new int[nums.length]; 5 max[0] = nums[0]; 6 min[0] = nums[0]; 7 int result = nums[0]; 8 for(int i = 1; i < nums.length; i++){ 9 max[i] = Math.max(Math.max(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]); 10 min[i] = Math.min(Math.min(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]); 11 result = Math.max(result, max[i]); 12 } 13 return result; 14 } 15 }
[leetcode]152. Maximum Product Subarray最大乘积子数组
标签:example number nta res inpu not ann int col
原文地址:https://www.cnblogs.com/liuliu5151/p/9206897.html