当前位置:网站首页>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;
}
}边栏推荐
- 【图像传感器】相关双采样CDS
- Vs2019 configuration matrix library eigen
- LocalStorage和SessionStorage
- 01tire+ chain forward star +dfs+ greedy exercise one
- Detailed explanation of several ideas for implementing timed tasks in PHP
- 删除 console 语句引发的惨案
- Module VI
- 一文读懂数仓中的pg_stat
- 二叉搜索树(特性篇)
- ByteDance Android gold, silver and four analysis, Android interview question app
猜你喜欢
随机推荐
正在准备面试,分享面经
射线与OBB相交检测
【DesignMode】模板方法模式(Template method pattern)
Record the migration process of a project
Laravel service provider instance tutorial - create a service provider test instance
ByteDance Android gold, silver and four analysis, Android interview question app
字节跳动Android金三银四解析,android面试题app
最新阿里P7技术体系,妈妈再也不用担心我找工作了
LeetCode-SQL第一天
【MySql进阶】索引详解(一):索引数据页结构
[designmode] proxy pattern
[summary of knowledge] summary of notes on using SVN in PHP
低代码(lowcode)帮助运输公司增强供应链管理的4种方式
Find tags in prefab in unity editing mode
谈谈 SAP 系统的权限管控和事务记录功能的实现
Vs2019 configuration matrix library eigen
Talk about the realization of authority control and transaction record function of SAP system
爬虫(17) - 面试(2) | 爬虫面试题库
"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
logback. XML configure logs of different levels and set color output
![[vulnhub range] thales:1](/img/fb/721d08697afe9b26c94fede628c4d1.png)







