当前位置:网站首页>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;
}
}边栏推荐
猜你喜欢

最新阿里P7技术体系,妈妈再也不用担心我找工作了

Personal notes of graphics (2)

Cesium(3):ThirdParty/zip. js

【MySql进阶】索引详解(一):索引数据页结构

Three. JS series (2): API structure diagram-2

Interface oriented programming

time标准库

Horizontal and vertical centering method and compatibility

Personal notes of graphics (1)

Opencv configuration 2019vs
随机推荐
Laravel post shows an exception when submitting data
Three. JS series (1): API structure diagram-1
[designmode] proxy pattern
二叉搜索树(特性篇)
偶然升职的内心独白
数据中台落地实施之法
Horizontal and vertical centering method and compatibility
如何快速检查钢网开口面积比是否符合 IPC7525
Introduction to ThinkPHP URL routing
3000 words speak through HTTP cache
node:504报错
[designmode] flyweight pattern
编程模式-表驱动编程
Laravel constructor and middleware execution order
最新2022年Android大厂面试经验,安卓View+Handler+Binder
Asyncio concept and usage
Balanced binary tree (AVL)
os、sys、random标准库主要功能
无法将“pip”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
Set the route and optimize the URL in thinkphp3.2.3