题目

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

  1. Input: [2,3,-2,4]
  2. Output: 6
  3. Explanation: [2,3] has the largest product 6.

Example 2:

  1. Input: [-2,0,-1]
  2. Output: 0
  3. Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

题意

在给定数组中找到一个子数组,使其积最大。

思路

动态规划。sm[i]表示以nums[i]为结尾的子数组能得到的最小乘积,lg[i]表示以nums[i]为结尾的子数组能得到的最大乘积。可以得到递推式:
0152. Maximum Product Subarray (M) - 图1


代码实现

Java

  1. class Solution {
  2. public int maxProduct(int[] nums) {
  3. int ans = nums[0];
  4. int[] sm = new int[nums.length];
  5. int[] lg = new int[nums.length];
  6. sm[0] = nums[0];
  7. lg[0] = nums[0];
  8. for (int i = 1; i < nums.length; i++) {
  9. sm[i] = Math.min(nums[i], Math.min(nums[i] * sm[i - 1], nums[i] * lg[i - 1]));
  10. lg[i] = Math.max(nums[i], Math.max(nums[i] * sm[i - 1], nums[i] * lg[i - 1]));
  11. ans = Math.max(ans, lg[i]);
  12. }
  13. return ans;
  14. }
  15. }