本文主要是介绍LeetCode 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
.
题目链接:https://leetcode.com/problems/maximum-product-subarray/
题目分析:维护当前的最大和最小,若当前为负数,最小值乘完会变大
public class Solution {public int maxProduct(int[] nums) {int n = nums.length;int ma = nums[0], mi = nums[0], ans = nums[0];for (int i = 1; i < n; i ++) {if (nums[i] < 0) {int tmp = mi;mi = ma;ma = tmp;}ma = Math.max(nums[i], ma * nums[i]);mi = Math.min(nums[i], mi * nums[i]);ans = Math.max(ans, ma);}return ans;}
}
这篇关于LeetCode 152 Maximum Product Subarray (思维)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!