2019.8.18 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
之前做过最大子序和LeetCode(53):最大子序和 Maximum Subarray(Java),这道题是最大子序积。这题也差不多,一维数组题大部分用动态规划的思路做。
由于数组存在负数,需要同时维护一个最大值max和一个最小值min,动态遍历每一个值i。动态更新的方程是
max = Math.max(nums[idx], max * nums[idx]);
min = Math.min(nums[idx], min * nums[idx]);
遇到负数则交换max和min,遇到0会自动更新为0.
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
/**
*
* Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
* 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
*
*/
public class MaximumProductSubarray {
public int maxProduct(int[] nums) {
int result = nums[0];
int max = nums[0];
int min = nums[0];
int idx = 1;
while(idx < nums.length){
//存在复数时将最大值和最小值交换
if(nums[idx] < 0){
int temp = max;
max = min;
min = temp;
}
max = Math.max(nums[idx], max * nums[idx]);
min = Math.min(nums[idx], min * nums[idx]);
result = result > max ? result : max;
idx++;
}
return result;
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#