当前位置:网站首页>LeetCode-152-乘积最大数组
LeetCode-152-乘积最大数组
2022-07-20 08:28:00 【z754916067】
题目
思路
- 第一反应还是dp,尝试做一下。dp不太能做出来,但是用普通的思想,将dp[i][j]视为nums数组从第i位到第j位的连续最大乘积,还是可以做出来的,但是这样暴力的话最后两个用例会超时。
for(int i=0;i<nums.length;i++){
for (int j =i;j< nums.length;j++){
if(i==j) dp[i][j]=nums[i];
else dp[i][j] = dp[i][j-1] * nums[j];
max = Math.max(max,dp[i][j]);
}
}
- 每轮都需要维护一个必须乘上nums[i]的最大值和最小值,所以在每轮开始之前要确定nums[i]的正负值,如果是负的则需要将最大值和最小值互换,然后才能开始算Max = Math.max(nums[i], Max*nums[i])等等,之后再维护即可;
代码
public int maxProduct(int[] nums) {
//返回的答案
int ans = Integer.MIN_VALUE;
//每一轮维护的最大值和最小值
int Max = 1;
int Min = 1;
for(int i=0;i< nums.length;i++){
//假设nums[i]是负数的话 很明显原本最大变最小 原本最小变最大 所以倒转过来
if(nums[i]<0){
int temp=Min;
Min = Max;
Max = temp;
}
//求出当前最大值和最小值
Max = Math.max(nums[i], Max*nums[i]);
Min = Math.min(nums[i], Min*nums[i]);
//最后维护返回的ans
ans = Math.max(ans,Max);
}
return ans;
}
边栏推荐
- Request和Response
- Make your ggplot2 support markdown syntax
- ASP. Net core using redis
- ByteDance (Tiktok) software test monthly salary 23K post, technical director three interview questions are newly released
- ASP. Net core custom Middleware
- 「接口测试入门课」打卡学习 day07:WebSocket接口:如何测试一个完全陌生的协议接口?
- Uniapp uses uni The solution to the request error {"errmsg": "request:fail abort statuscode:-1"}
- UML图系列之序列图
- Calculating definite integral with R language
- flv封装解析
猜你喜欢
JUC包下的常见类
Scala variables and data types (01)
ASP. Net core using Autofac
Girls who have just started the software testing industry can get a monthly salary of more than 10000 to solve the mystery of the fraud
R language RMD output has Chinese, how to remove Chinese
Spss-kmeans聚类分析操作
如何使用Blender制作360度全景图和全景视频?
Add another article ----- printf
TP5.1 登录 配置是否登录公共函数的方法(完整的登录案例)
经典网络学习-ResNet代码实现
随机推荐
R 语言求最值问题
【C语言刷LeetCode】731. 我的日程安排表 II(M)
In the second quarter of 2022, Web3 became the most interesting area for encryption venture capital
R语言 | jiebaR 词频统计
点播 构造自己的播放器 用户调用获取视频播放地址接口
Console C # flying chess small project
Drawing multi group Y-axis truncation graph with R language
The best method of converting string to date in R language
Detailed explanation of x509 digital certificate
R language string is the best way to mention numbers and dates
R language optimization problem
Scala variables and data types (01)
Tp5.1 open the web address and output the web page code without transformation and rendering (template return $this- & gt; fetch() return view();)
sql server 2022 安装
R语言中插补缺失值的R包simputation
[C language brush leetcode] 729 My schedule I (m)
Rmarkdown与Word文档的交互
Php obtient le Répertoire racine du site Web, plusieurs méthodes PHP obtient le Répertoire racine du site Web
Introduction to the basic use of openresty
R语言快速绘制多因素回归分析森林图