栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode

目录
  • 1.题目
  • 2.思路
  • 3.代码实现(Java)

1.题目

给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。

测试用例的答案是一个 32-位 整数。

子数组是数组的连续子序列。

示例 1:
输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。

示例 2:
输入: nums = [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

提示:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
nums 的任何前缀或后缀的乘积都 保证 是一个 32-位 整数

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-product-subarray

2.思路

(1)暴力穷举法
(2)动态规划
思路参考本题官方题解。

3.代码实现(Java)
//思路1————暴力穷举法
public int maxProduct(int[] nums) {
	//res 保存乘积最大子数组所对应的乘积,初始值为 Integer.MIN_VALUE
    int res = Integer.MIN_VALUE;
    int length = nums.length;
    //循环穷举所有的子数组,并用 res 保存乘积最大子数组所对应的乘积
    for (int  i = 0; i < length; i++) {
        int tmp = nums[i];
        res = Math.max(res, nums[i]);
        for (int j = i + 1; j < length; j++) {               
            tmp *= nums[j];
            res = Math.max(res, tmp);
        }
    }
    return res;
}
//思路2————动态规划
public int maxProduct(int[] nums) {
    int res = Integer.MIN_VALUE;
    int length = nums.length;
    
    int[] maxF = new int[length];
    int[] minF = new int[length];
    System.arraycopy(nums, 0, maxF, 0, length);
    System.arraycopy(nums, 0, minF, 0, length);
    for (int i = 1; i < length; i++) {
        maxF[i] = Math.max(maxF[i - 1] * nums[i], Math.max(nums[i], minF[i - 1] * nums[i]));
        minF[i] = Math.min(minF[i - 1] * nums[i], Math.min(nums[i], maxF[i - 1] * nums[i]));
    }
    res = maxF[0];
    for (int i = 1; i < length; i++) {
        res = Math.max(res, maxF[i]);
    }
    return res;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915371.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号