当前位置:网站首页>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;
}
}
边栏推荐
- Personal notes of graphics (2)
- The difference and working principle between compiler and interpreter
- 模块六
- 01tire+链式前向星+dfs+贪心练习题.1
- What is the difference between IP address and physical address
- Lowcode: four ways to help transportation companies enhance supply chain management
- 【C 语言】 题集 of Ⅹ
- QT中自定义控件的创建到封装到工具栏过程(二):自定义控件封装到工具栏
- 预测——灰色预测
- Pycharm terminal enables virtual environment
猜你喜欢
null == undefined
3000 words speak through HTTP cache
无法将“pip”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
字节跳动Android面试,知识点总结+面试题解析
Master this promotion path and share interview materials
Personal notes of graphics (2)
网关Gateway的介绍与使用
The latest interview experience of Android manufacturers in 2022, Android view+handler+binder
模块六
【C 语言】 题集 of Ⅹ
随机推荐
Pycharm terminal enables virtual environment
Usage of config in laravel
AutoLISP series (2): function function 2
Lowcode: four ways to help transportation companies enhance supply chain management
Ray and OBB intersection detection
Personal notes of graphics (2)
【C 语言】 题集 of Ⅹ
模拟Servlet的本质
[vulnhub range] thales:1
[designmode] facade patterns
Set the route and optimize the URL in thinkphp3.2.3
数据中台落地实施之法
The latest interview experience of Android manufacturers in 2022, Android view+handler+binder
Laravel5.1 Routing - routing packets
【DesignMode】外观模式 (facade patterns)
JS modularization
typescript ts基础知识之tsconfig.json配置选项
Geoserver2.18 series (5): connect to SQLSERVER database
logback.xml配置不同级别日志,设置彩色输出
字节跳动Android金三银四解析,android面试题app