[Lintcode]Maximum Product Subarray乘积最大子序列

来源:互联网 发布:js ajax获取网页 编辑:程序博客网 时间:2024/06/06 12:02

Find the contiguous subarray within an array (containing at least one number) which has the largest product.


Example

For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.

分析:构建二维数组。res[i][j]代表从i到j连乘结果。结果:超过内存限制

public class Solution {    /**     * @param nums: an array of integers     * @return: an integer     */    public int maxProduct(int[] nums) {        if(nums.length == 0) return 0;                int[][] res = new int[nums.length][nums.length];                int max = Integer.MIN_VALUE;        for(int i = 0; i < nums.length; i++) {            res[i][i] = nums[i];            max = Math.max(max, res[i][i]);            for(int j = i + 1; j < nums.length; j++) {                res[i][j] = res[i][j - 1] * nums[j];                max = Math.max(max, res[i][j]);            }                    }        return max;    }}

看了一下,二维数组多余。直接用一个int代替。通过。

public class Solution {    /**     * @param nums: an array of integers     * @return: an integer     */    public int maxProduct(int[] nums) {        if(nums.length == 0) return 0;                int max = Integer.MIN_VALUE;        for(int i = 0; i < nums.length; i++) {            int start = nums[i];            max = Math.max(max, start);            for(int j = i + 1; j < nums.length; j++) {                start = start * nums[j];                max = Math.max(max, start);            }                    }        return max;    }}


0 0
原创粉丝点击