当前位置:网站首页>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] <= 10nums的任何前缀或后缀的乘积都 保证 是一个 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;
}
}
边栏推荐
- JWT 实现登录认证 + Token 自动续期方案
- Redis(三)——配置文件详解、发布和订阅、新数据类型
- Codeforces 814 C. An impassioned circulation of affection (dp)
- Break through the dimensional barriers and let the dolls around you move on the screen!
- database transaction
- Gartner reiterates the important value of 'data weaving'
- database constraints
- Regarding the missing json converter, the error message is: No converter found for return value of type
- Open Office XML 格式里如何描述多段具有不同字体设置的段落
- 2022.8.9-----leetcode.1413
猜你喜欢

PPT | 「课件」企业中高层人员安全管理培训(118页)

「首席工程师」首席(Principal )工程师修炼之道

动作捕捉系统用于室内组合定位技术研究

AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)

谷歌数据中心发生“电力事故”造成 3 人受伤

Pycharm终端出现PS问题、conda或activate不是内部命令问题..

Automated Testing and Selenium

Emulate stm32 directly with proteus - the programmer can be completely discarded

Weilai-software development engineer side record

3D旋转文本动画js特效
随机推荐
Text selection rounded style border-radius
从产品维度来看 我们为什么不能完全信任Layer2?
OneFlow源码解析:算子指令在虚拟机中的执行
POJ 1026 Cipher (置换群)
自动化测试及Selenium
Weilai-software development engineer side record
企业如何判断数据治理是否成功?
ECCV 2022 | 视频理解新框架X-CLIP:仅用微调的成本,达到预训练的全能
商城限时秒杀功能系统
runtime-core.esm-bundler.js?d2dd:218 Uncaught TypeError: formRef.value?.validate is not a function
[C language] Header file #include
, conio is Console Input/Output (console input and output) 【Azure云】服务端点和私有链接有什么区别?观点(1)
js对象转FormData对象(一般用于上传)
干货!ASSANet:让PointNet++更快更强
C#List的使用以及Linq的使用
网络文化经营许可证
OneFlow source code parsing: operator instructions executed in a virtual machine
Gartner reiterates the important value of 'data weaving'
【无标题】
Redis设计与实现