当前位置:网站首页>左右最值最大差问题
左右最值最大差问题
2022-07-04 18:48:00 【GreyZeng】
左右最值最大差问题
作者:Grey
原文地址: 左右最值最大差问题
题目链接
描述
给定一个长度为N(N>1)的整型数组A,可以将A划分成左右两个部分,左部分
A[0..K]
,右部分A[K+1..N-1]
,K可以取值的范围是[0,N-2]
。求这么多划分方案中,左部分中的最大值减去右部分最大值的绝对值,最大是多少?
给定整数数组A和数组的大小n,请返回题目所求的答案。
测试样例:
A:[2,7,3,1,1]
n:5
返回:6
主要思路
假设数组长度为len
,遍历一遍数组,得到数组的最大值max
,然后比较0
位置和len-1
位置的值,取较小的那个,假设为m
,则max - m
即为答案。
完整代码
public class MaxGap {
public int findMaxGap(int[] A, int n) {
int max = A[0];
int len = A.length;
for (int i = 1; i < len; i++) {
max = Math.max(A[i], max);
}
return max - (Math.min(A[0], A[len - 1]));
}
}
证明
由于全局最大值是max
,所以无论max
被划分到哪个部分,都会成为这部分的最大值。假设max
被划分到了右边部分,所以右边部分的最大值就是max
,假设左边部分的最大值是m
,那么max - m
即为一个答案候选。要使得max - m
最大,而左边部分不能为空,所以左边部分必须要包含0
位置的值,所以,在左边只包含0
位置值的时候,max - m
才能做到最大,即:max - arr[0]
;同理,假设max
被划分到了左边,右边最大值假设为n
,要使得max - n
最大,len - 1
位置的值又必须包含在右边,那么max - arr[len-1]
才是最大的。所以最终的答案就是:
max - Math.min(arr[0],arr[len-1]);
更多
边栏推荐
- Selected review | machine learning technology for Cataract Classification / classification
- ICML 2022 | Meta提出鲁棒的多目标贝叶斯优化方法,有效应对输入噪声
- Kotlin condition control
- On communication bus arbitration mechanism and network flow control from the perspective of real-time application
- Pointnet / pointnet++ point cloud data set processing and training
- 记一次 .NET 某工控数据采集平台 线程数 爆高分析
- Qt编写物联网管理平台38-多种数据库支持
- TCP waves twice, have you seen it? What about four handshakes?
- Employment prospects of neural network Internet of things application technology [welcome to add]
- Cbcgptabwnd control used by BCG (equivalent to MFC TabControl)
猜你喜欢
YOLOv5s-ShuffleNetV2
MySQL中的日期时间类型与格式化方式
What does the neural network Internet of things mean? Popular explanation
精选综述 | 用于白内障分级/分类的机器学习技术
ICML 2022 | Meta提出鲁棒的多目标贝叶斯优化方法,有效应对输入噪声
C # use stopwatch to measure the running time of the program
c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
C language - Introduction - Foundation - grammar - process control (VII)
What is the application technology of neural network and Internet of things
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
随机推荐
太方便了,钉钉上就可完成代码发布审批啦!
Crystal optoelectronics: ar-hud products of Chang'an dark blue sl03 are supplied by the company
输入的查询SQL语句,是如何执行的?
记一次 .NET 某工控数据采集平台 线程数 爆高分析
The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!
Niuke Xiaobai month race 7 who is the divine Archer
In the first month of its launch, the tourist praise rate of this campsite was as high as 99.9%! How did he do it?
What is involution?
软件客户端数字签名一定要申请代码签名证书吗?
紫光展锐完成全球首个 5G R17 IoT NTN 卫星物联网上星实测
做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
1011 World Cup betting (20 points) (pat a)
数据集划分
Actual combat simulation │ JWT login authentication
Lingyun going to sea | Murong Technology & Huawei cloud: creating a model of financial SaaS solutions in Africa
So this is the BGP agreement
长城证券开户安全吗 股票开户流程网上开户
node强缓存和协商缓存实战示例
Thinking on demand development
Multi table operation inner join query