2. 偶數個 neg 時可能會產生 max 值, 解法是紀錄 max 和 min value, 如果neg*neg 時就會產生 max 值
idea -
max( max product, min product, current value),
min( max product, min product, current value),
because of negative*negative may generate max number!
最後取最大值
time: O(n)
space: O(1)
classSolution {publicintmaxProduct(int[] nums) {int max = nums[0];int min = nums[0];int res = nums[0];for (int i =1; i <nums.length; i++) {int temp = max; max =Math.max(Math.max(nums[i]*max, nums[i]*min), nums[i]); min =Math.min(Math.min(nums[i]*temp, nums[i]*min), nums[i]); res =Math.max(res, max); }return res; }}
original DP
classSolution {publicintmaxProduct(int[] nums) {// [-2,0,-1], max = 0, // 2 3 -3 4 max = 6// 2 -3 -3 4 max = 72 , so when even neg, will have max value// 2 -3 [-3 4 -3 -2 1 -4] max = 36* 8int dpMax[] =newint[nums.length];int dpMin[] =newint[nums.length]; dpMax[0] = nums[0]; dpMin[0] = nums[0];int res = nums[0];for (int i =1; i <nums.length; i++) { dpMax[i] =Math.max(Math.max(nums[i]*dpMax[i-1], nums[i]*dpMin[i-1]), nums[i]) ; dpMin[i] =Math.min(Math.min(nums[i]*dpMax[i-1], nums[i]*dpMin[i-1]), nums[i]); res =Math.max(res, dpMax[i]); }return res; }}
then use variables, or like first one way
classSolution {publicintmaxProduct(int[] nums) {int max = nums[0];int min = nums[0];int res = nums[0];for (int i =1; i <nums.length; i++) {int newMax =Math.max(Math.max(nums[i]*max, nums[i]*min), nums[i]) ;int newMin =Math.min(Math.min(nums[i]*max, nums[i]*min), nums[i]); max = newMax; min = newMin; res =Math.max(res, max); }return res; }}