当前位置:网站首页>LeetCode_152_乘积最大子数组
LeetCode_152_乘积最大子数组
2022-08-10 10:43:00 【Fitz1318】
题目链接
题目描述
给你一个整数数组 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 * 10^4
-10 <= nums[i] <= 10
nums
的任何前缀或后缀的乘积都 保证 是一个 32-位 整数
解题思路
动态规划
- 遍历数组时计算当前最大值,不断更新
- 令curMax 为当前最大值,那么
curMax = Math.max(curMax * nums[i], nums[i]);
- 令curMin为当前最小值,那么
curMin = Math.min(curMin * nums[i], nums[i]);
AC代码
class Solution {
public int maxProduct(int[] nums) {
int ans = nums[0];
int curMax = nums[0];
int curMin = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < 0) {
// 当出现负数时,会导致最大的边最小的,最小的变最大的
int tmp = curMax;
curMax = curMin;
curMin = tmp;
}
curMax = Math.max(curMax * nums[i], nums[i]);
curMin = Math.min(curMin * nums[i], nums[i]);
ans = Math.max(ans, curMax);
}
return ans;
}
}
边栏推荐
猜你喜欢
Weilai-software development engineer side record
技能大赛训练题:组策略一
Open Office XML 格式里如何描述多段具有不同字体设置的段落
STM32封装ESP8266一键配置函数:实现实现AP模式和STA模式切换、服务器与客户端创建
C#实战:基于ItextSharp技术标签生成小工具
短视频软件开发——平台同质化如何破局
什么是抽象类
第5章相似矩阵及二次型(4)
AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)
干货!ASSANet:让PointNet++更快更强
随机推荐
mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded
越折腾越好用的 3 款开源 APP
企业如何判断数据治理是否成功?
Pycharm终端出现PS问题、conda或activate不是内部命令问题..
Codeforces 814 C. An impassioned circulation of affection (dp)
mysql5.7 installation and deployment - yum installation
3D rotating text animation js special effects
String interception function in SQL
面试官:项目中 Dao、Service、Controller、Util、Model 怎么划分的?
Redis(三)——配置文件详解、发布和订阅、新数据类型
2022.8.7-----leetcode.636
"Data Strategy" Results-Driven Enterprise Data Strategy: Organization and Governance
GPU accelerated Pinterest recommendation model, the number of parameters increased by 100 times, and the user activity increased by 16%
OneFlow源码解析:算子指令在虚拟机中的执行
Double.doubleToLongBits() method uses
Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户
POJ 1026 Cipher (置换群)
【FAQ】【Push Kit】 华为怎么设置角标
Summary of whitespace, space and escape characters in C language
"Scalability" extensibility best practices: lessons from eBay