LeetCode152——乘积最大子序列

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/86261978

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/maximum-product-subarray/description/

题目描述:

知识点:动态规划

思路一:暴力破解法

时间复杂度是O(n ^ 2),其中n是nums数组中的元素个数。空间复杂度是O(1)。

JAVA代码:

public class Solution {
    public int maxProduct(int[] nums) {
        int result = Integer.MIN_VALUE;
        for(int i = 0; i < nums.length; i++){
            int temp = 1;
            for(int j = i; j < nums.length; j++){
                temp *= nums[j];
                if(temp > result){
                    result = temp;
                }
            }
        }
        return result;
    }
}

LeetCode解题报告:

思路二:动态规划

状态定义

f(x) -------- nums数组中[0, x]范围内的最大连续子序列的乘积,且该连续子序列以nums[x]结尾

g(x) -------- nums数组中[0, x]范围内的最小连续子序列的乘积,且该连续子序列以nums[x]结尾

状态转移

(1)当x等于0时,显然此时[0, x]范围内只有一个元素,f(0)和g(0)均等于这个唯一的元素。

(2)当x大于0时

a:如果nums[x] >= 0,f(x) = max(f(x - 1) * nums[x], nums[x]),g(x) = min(g(x - 1) * nums[x], nums[x])

b:如果nums[x] < 0,f(x) = max(g(x - 1) * nums[x], nums[x]),g(x) = min(f(x - 1) * nums[x], nums[x])

时间复杂度和空间复杂度均为O(n),其中n是nums数组中的元素个数。

JAVA代码:

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

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/86261978
今日推荐