当前位置:网站首页>左右最值最大差问题
左右最值最大差问题
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]);
更多
边栏推荐
- Small hair cat Internet of things platform construction and application model
- FS4061A升压8.4V充电IC芯片和FS4061B升压12.6V充电IC芯片规格书datasheet
- Dynamic memory management
- 实践示例理解js强缓存协商缓存
- [problem] Druid reports exception SQL injection violation, part always true condition not allow solution
- Crystal optoelectronics: ar-hud products of Chang'an dark blue sl03 are supplied by the company
- 泰山OFFICE技术讲座:关于背景(底纹和高亮)的顺序问题
- 【ISMB2022教程】图表示学习的精准医疗,哈佛大学Marinka Zitnik主讲,附87页ppt
- 凌云出海记 | 文华在线&华为云:打造非洲智慧教学新方案
- [today in history] July 4: the first e-book came out; The inventor of magnetic stripe card was born; Palm computer pioneer was born
猜你喜欢

太方便了,钉钉上就可完成代码发布审批啦!
实践示例理解js强缓存协商缓存

Chrome development tool: what the hell is vmxxx file

C语言-入门-基础-语法-流程控制(七)

Huawei Nova 10 series supports the application security detection function to build a strong mobile security firewall

Employment prospects and current situation of Internet of things application technology

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?

输入的查询SQL语句,是如何执行的?

c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)

精选综述 | 用于白内障分级/分类的机器学习技术
随机推荐
Informatics Olympiad 1336: [example 3-1] find roots and children
被奉为经典的「金字塔原理」,教给我们哪些PPT写作技巧?
In operation (i.e. included in) usage of SSRs filter
What ppt writing skills does the classic "pyramid principle" teach us?
Integretee integrates into Moonriver through xcm, bringing enterprise class privacy solutions to its ecosystem
What is involution?
[QNX Hypervisor 2.2用户手册]6.3.1 工厂页和控制页
Dynamic memory management
New wizard effect used by BCG
ICML 2022 | Meta提出鲁棒的多目标贝叶斯优化方法,有效应对输入噪声
上线首月,这家露营地游客好评率高达99.9%!他是怎么做到的?
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
实战模拟│JWT 登录认证
Kotlin classes and objects
Swagger suddenly went crazy
HMM hidden Markov model and code implementation
Neural network IOT platform construction (IOT platform construction practical tutorial)
凌云出海记 | 文华在线&华为云:打造非洲智慧教学新方案
Related concepts of federal learning and motivation (1)
九齐单片机NY8B062D单按键控制4种LED状态