152. Maximum Product Subarray

网友投稿 622 2022-09-04

152. Maximum Product Subarray

152. Maximum Product Subarray

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.

class Solution { public int maxProduct(int[] nums) { int[] max = new int[nums.length]; int[] min = new int[nums.length]; min[0] = max[0] = nums[0]; int result = nums[0]; for (int i = 1; i < nums.length; i++) { min[i] = max[i] = nums[i]; if (nums[i] > 0) { max[i] = Math.max(max[i], max[i - 1] * nums[i]); min[i] = Math.min(min[i], min[i - 1] * nums[i]); } else if (nums[i] < 0) { max[i] = Math.max(max[i], min[i - 1] * nums[i]); min[i] = Math.min(min[i], max[i - 1] * nums[i]); } result = Math.max(result, max[i]); } return result; } }

class Solution { public int maxProduct(int[] nums) { int[] max= new int[a.length]; int[] min = new int[a.length]; max[0]=a[0]; min[0]=a[0]; for(int i=1;i

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:114. Flatten Binary Tree to Linked List
下一篇:24 个必须掌握的数据库面试问题!(24小时天气预报)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~