[LC] 152. Maximum Product Subarray
2024-08-31 10:54:38
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output:6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = nums[0];
int min = nums[0];
int res = nums[0];
int preMax = max;
for (int i = 1; i < nums.length; i++) {
// include the current for comparison
max = Math.max(nums[i], Math.max(preMax * nums[i], min * nums[i]));
min = Math.min(nums[i], Math.min(min * nums[i], preMax * nums[i]));
res = Math.max(max, res);
preMax = max;
}
return res;
}
}
最新文章
- Unity 处理IOC AOP
- AngularJS SQL 获取数据
- WIN 程序员的 Linux 互斥类
- c++对象创建带括号与无括号的区别
- css3立体旋转动画
- 移动设备页面高度不足时min-height 的尴尬处理
- WebStorm 8 注册码
- JSP动作跳转页面的时候与根目录的问题
- C#操作ini
- fekit前端代码模块化工具
- 在VS上配置OpenCV
- 【ASP.NET Web API教程】2.4 创建Web API的帮助页面
- 【淡墨Unity3D Shader计划】五 圣诞用品: Unity在Shader三种形式的控制&;amp;混合操作编译
- SQL SERVER:CASE判断空,错误一例
- javascript痛点之三闭包
- Tomcat 启动时 SecureRandom 非常慢解决办法,亲测有效
- 前后台分离开发时遇到循环引用问题";$ref";
- Vue SSR不可不知的问题
- 关于一体机外卖单不打印外卖单号FAQ(适用正餐6.0.09,轻餐4.0.6.1,轻餐4.0.6.2)
- Codeforces 1045B Space Isaac