当前位置:网站首页>左右最值最大差问题
左右最值最大差问题
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]);
更多
边栏推荐
- PHP pseudo original API docking method
- Neural network IOT platform construction (IOT platform construction practical tutorial)
- 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?
- 1500万员工轻松管理,云原生数据库GaussDB让HR办公更高效
- Niuke Xiaobai month race 7 e applese's super ability
- 漫谈客户端存储技术之Cookie篇
- 原来这才是 BGP 协议
- ACM组合计数入门
- 华为云云商店首页 Banner 资源位申请
- Oracle database, numbers Force 2 decimal places to display-Alibaba Cloud
猜你喜欢
【历史上的今天】7 月 4 日:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生
上线首月,这家露营地游客好评率高达99.9%!他是怎么做到的?
node强缓存和协商缓存实战示例
Development and construction of DFI ecological NFT mobile mining system
How to adapt your games to different sizes of mobile screen
Huawei Nova 10 series supports the application security detection function to build a strong mobile security firewall
Optimization cases of complex factor calculation: deep imbalance, buying and selling pressure index, volatility calculation
Multi table operation inner join query
What should we pay attention to when doing social media marketing? Here is the success secret of shopline sellers!
Actual combat simulation │ JWT login authentication
随机推荐
What is involution?
Chrome development tool: what the hell is vmxxx file
Six stones programming: about code, there are six triumphs
Qt编写物联网管理平台38-多种数据库支持
【毕业季】绿蚁新醅酒,红泥小火炉。晚来天欲雪,能饮一杯无?
更强的 JsonPath 兼容性及性能测试之2022版(Snack3,Fastjson2,jayway.jsonpath)
多表操作-内连接查询
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
复杂因子计算优化案例:深度不平衡、买卖压力指标、波动率计算
kotlin 继承
Abc229 summary (connected component count of the longest continuous character graph in the interval)
Swagger suddenly went crazy
New wizard effect used by BCG
【深度学习】一文看尽Pytorch之十九种损失函数
Basic use of kotlin
实战模拟│JWT 登录认证
Related concepts of federal learning and motivation (1)
为什么最大速度是光速
Small hair cat Internet of things platform construction and application model
Actual combat simulation │ JWT login authentication