当前位置:网站首页>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;
}
}
边栏推荐
- 谷歌数据中心发生“电力事故”造成 3 人受伤
- FastReport.Net 2022.2.17 Crack
- The impact of development mode on testing
- AUTOCAD——减少样条曲线控制点数、CAD进阶练习(三)
- Load balancing principle analysis and source code interpretation
- 商城限时秒杀功能系统
- 阻塞 非阻塞 poll机制 异步
- bus event bus use
- Techches Transformer the join wisdom source the author cao, visual basic model study
- js猜拳小游戏源码
猜你喜欢
Redis(三)——配置文件详解、发布和订阅、新数据类型
STM32 encapsulation ESP8266 a key configuration function: implementations of AP mode and the STA mode switch, server and the client to create
使用cpolar远程连接群晖NAS(升级固定链接2)
Redis设计与实现
Some tips for using Unsafe
[Microservice Architecture] Microservices and SOA Architecture (2)
「时序数据库」使用cassandra进行时间序列数据扫描
Network Security Note 6 - Digital Certificates and Public Key Infrastructure
js猜拳小游戏源码
【Azure云】服务端点和私有链接有什么区别?观点(1)
随机推荐
Redis (six) - transaction and lock mechanism of Redis6 (unfinished, to be supplemented)
快速上手,征服三种不同分布式架构调用方案
【勇敢饭饭,不怕刷题之链表】有序链表的合并
The impact of development mode on testing
Dalian University of Technology & Pengcheng & UAE propose a mixed-scale triple network ZoomNet for camouflaged target detection, with SOTA performance!
In August the DB list latest scores - database Engines
WebView2 通过 PuppeteerSharp 实现爬取 王者 壁纸 (案例版)
Situation丨The intrusion of hackers intensifies, and the shooting range sets up a "defense shield" for network security
一文带你搞懂中断按键驱动程序之poll机制
owl.carousel海报卡片Slider轮播切换
From the product dimension, why can't we fully trust Layer2?
Unsafe的一些使用技巧
js猜拳小游戏源码
Automated Testing and Selenium
面试官:项目中 Dao、Service、Controller、Util、Model 怎么划分的?
bus事件总线 使用
OneFlow源码解析:算子指令在虚拟机中的执行
Redis6(一)——NoSQL数据库简介与Redis的安装
PPT | 「课件」企业中高层人员安全管理培训(118页)
从产品维度来看 我们为什么不能完全信任Layer2?