【LeetCode】【Solution】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.

【解法】

参考 http://segmentfault.com/blog/riodream/1190000000691766

public class Solution {
    public int maxProduct(int[] A) {
        if (A.length == 0) return 0;
        if (A.length == 1) return A[0];

        int max_ending_here = 0;
        int min_ending_here = 0;
        int max_so_far = 0;

        for (int i = 0; i < A.length; i++) {
            if (A[i] > 0) {
                max_ending_here = Math.max(max_ending_here * A[i], A[i]);
                min_ending_here = Math.min(min_ending_here * A[i], A[i]);
            } else if (A[i] == 0) {
                max_ending_here = 0;
                min_ending_here = 0;
            } else {
                int temp = max_ending_here;
                max_ending_here = Math.max(min_ending_here*A[i], A[i]);
                min_ending_here = Math.min(temp * A[i], A[i]);
            }

            if (max_ending_here > max_so_far) {
                max_so_far = max_ending_here;
            }
        }

        return max_so_far;
    }
}

【标准Solution】

Let us denote that:

f(k) = Largest product subarray, from index 0 up to k.

Similarly,

g(k) = Smallest product subarray, from index 0 up to k.

Then,

f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] )
g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] )

上面就是动规方程。

public int maxProduct(int[] A) {
   assert A.length > 0;
   int max = A[0], min = A[0], maxAns = A[0];
   for (int i = 1; i < A.length; i++) {
      int mx = max, mn = min;
      max = Math.max(Math.max(A[i], mx * A[i]), mn * A[i]);
      min = Math.min(Math.min(A[i], mx * A[i]), mn * A[i]);
      maxAns = Math.max(max, maxAns);
   }
   return maxAns;
}

【声明】本博客只是用于学习和交流,如不小心侵犯了您的权益,请联系本人,我会及时处理,谢谢!

时间: 2024-10-10 20:38:39

【LeetCode】【Solution】Maximum Product Subarray的相关文章

【LeetCode】Maximum Product Subarray 求连续子数组使其乘积最大

Add Date 2014-09-23 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 = 

【leetcode刷题笔记】Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 题解:递归,树的高度 = max(左子树高度,右子树高度)+1: 代码如下: 1 /** 2 * Definition for binary tree 3 * public cla

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note:You may not engage in multiple transactions at the same time (ie,

【leetcode刷提笔记】Container With Most Water

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a containe

【leetcode刷题笔记】Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example:A = 

【leetcode刷题笔记】Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和