当前位置:网站首页>LeetCode 152. 乘积最大子数组 每日一题
LeetCode 152. 乘积最大子数组 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
给你一个整数数组 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int maxProduct(int[] nums) {
if(nums.length == 1) return nums[0];
int ans = 0;
int positive = 1;
int negative = 1;
for(int n : nums){
if(positive <= 0) positive = 1;
if(negative >= 0) negative = 1;
if(n < 0){
int t = negative;
negative = positive * n;
positive = t * n;
}else {
negative *= n;
positive *= n;
}
if(positive > ans) ans = positive;
}
return ans;
}
}边栏推荐
- Spark Tuning (III): persistence reduces secondary queries
- Laravel changed the session from file saving to database saving
- Common training data set formats for target tracking
- 最新2022年Android大厂面试经验,安卓View+Handler+Binder
- 记录Servlet学习时的一次乱码
- 应用在温度检测仪中的温度传感芯片
- Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions
- Balanced binary tree (AVL)
- Laravel post shows an exception when submitting data
- 两类更新丢失及解决办法
猜你喜欢
随机推荐
[Android -- data storage] use SQLite to store data
The difference and working principle between compiler and interpreter
值得一看,面试考点与面试技巧
Read PG in data warehouse in one article_ stat
Arduino 控制的双足机器人
【DesignMode】享元模式(Flyweight Pattern)
"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
LeetCode 403. 青蛙过河 每日一题
[designmode] template method pattern
作为Android开发程序员,android高级面试
Personal notes of graphics (2)
删除 console 语句引发的惨案
[designmode] proxy pattern
LocalStorage和SessionStorage
dapp丨defi丨nft丨lp单双币流动性挖矿系统开发详细说明及源码
应用在温度检测仪中的温度传感芯片
Introduction to ThinkPHP URL routing
Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions
Three. JS series (1): API structure diagram-1
Leetcode-136- number that appears only once (solve with XOR)









