当前位置:网站首页>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;
}
}
边栏推荐
- 蔚来-软件开发工程师一面记录
- 【Azure云】服务端点和私有链接有什么区别?观点(1)
- MongoDB数据库笔记
- C#实战:基于ItextSharp技术标签生成小工具
- AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)
- Emulate stm32 directly with proteus - the programmer can be completely discarded
- Codeforces 814 C. An impassioned circulation of affection (dp)
- owl.carousel海报卡片Slider轮播切换
- blocking non-blocking poll mechanism asynchronous
- ISO9001在讲什么?过程方法和风险思维
猜你喜欢

文本选中圆角样式border-radius

In August the DB list latest scores - database Engines

让软件飞——“X+”技术揭秘

Redis(三)——配置文件详解、发布和订阅、新数据类型

Redis6 (1) - Introduction to NoSQL Database and Installation of Redis

MongoDB数据库笔记

"Chief Engineer" Principal (Principal) engineer's way of training

AUTOCAD——减少样条曲线控制点数、CAD进阶练习(三)

什么是抽象类

"MySQL Advanced Chapter" 6. Principles of index creation and design
随机推荐
【勇敢饭饭,不怕刷题之链表】链表反转的几种情况
[Azure Cloud] What is the difference between a service endpoint and a private link?point of view (1)
JWT implements login authentication + Token automatic renewal scheme
【FAQ】【Push Kit】 华为怎么设置角标
POJ 3101 Astronomy (数学)
[Microservice Architecture] Microservices and SOA Architecture (2)
"Data Strategy" Results-Driven Enterprise Data Strategy: Organization and Governance
MongoDB数据库笔记
Pycharm终端出现PS问题、conda或activate不是内部命令问题..
Redis (three) - detailed configuration file, publish and subscribe, new data types
第二十二章 源代码文件 REST API 参考(四)
js guessing game source code
POJ 1026 Cipher (置换群)
什么是抽象类
第5章相似矩阵及二次型(4)
Double.doubleToLongBits()方法使用
owl.carousel海报卡片Slider轮播切换
Text selection rounded style border-radius
Gartner再次重申了“数据编织”的重要价值
EasyCVR级联时,修改下级平台名称将不同步至上级平台