当前位置:网站首页>左右最值最大差
左右最值最大差
2022-06-09 12:40:00 【little-peter】
给定一个长度为N(N>1)的整型数组A,可以将A划分成左右两个部分,左部分A[0…K],右部分A[K+1…N-1],K可以取值的范围是[0,N-2]。求这么多划分方案中,左部分中的最大值减去右部分最大值的绝对值,最大是多少?
给定整数数组A和数组的大小n,请返回题目所求的答案。
测试样例:
[2,7,3,1,1],5
返回:6
思路:基于贪心算法的思想 这两个数中有一个肯定是数组的最大值。要使得差值最大,那么另一边的最大值应尽可能的小。 假设最大值在左边,那么对于最大值右边的数组有很多种分法,每一种分法肯定都包含数组最后一个数字即A[n-1]。 如果不取A[n-1],取最后一个数字和最大值中间的任一数字A[i]。 若A[i]大于A[n-1],那还不如取最后一个数字;
若最A[i] 小于A[n-1], 那右半边的最大值肯定不是A[i],所以无论如何右半边取最右端数字。 假设最大值在右边,同理左半边取最左端数字。 只需用数组最大值减去数组两端较小的那个值即可。
- 实现
代码:
import java.util.*;
public class MaxGap {
public int findMaxGap(int[] A, int n) {
int max=A[0];
int min=A[0]>A[n-1]?A[n-1]:A[0];
for(int i=0;i<n;i++){
if(A[i]>max){
max=A[i];
}
}
return max-min;
}
}
边栏推荐
- 斯坦福博士提出超快省显存Attention,GPT-2训练速度提升3.5倍,BERT速度创纪录
- How to do data visualization analysis
- 云呐|如何做好固定资产盘点?怎么盘点固定资产
- Development and present situation of Network Space Surveying and mapping at home and abroad
- Zhoubolei annual progress overview of model interpretability 20200805
- pytorch:子模型参数冻结 + BN冻结
- 论文阅读《LEAStereo:Hierarchical Neural Architecture Search for Deep Stereo Matching》
- 云呐|服务器监控可视化工具
- [C language practice - adjust the order of odd and even numbers in the array]
- 2022.6.3-----leetcode.829
猜你喜欢

Hit the snake seven inches

Hype plagiarism, insider fraud common NFT scams and security suggestions on opensea

从最优化的角度看待Softmax损失函数

Zhoubolei annual progress overview of model interpretability 20200805

不看全图看局部,CNN性能竟然更强了

他26岁,发表论文18篇,刚把上世纪的素数猜想给证明了

Network attacks focus on people's livelihood. How can we effectively defend against DDoS and apt attacks?

How to solve the worry of enterprise network with the acceleration of cloud network integration on the third anniversary of 5g licensing?

Database day-2
![[C language practice - printing square and its deformation]](/img/20/51a3f5d104275026605db268b64607.png)
[C language practice - printing square and its deformation]
随机推荐
BI报表系统有什么特点
2022.5.26-----leetcode.699
k8s中的postgresql怎么导出查询的结果,并导入到本地windows机器上的数据库
数字化转型:如何获得组织的认可?
Comment résoudre le problème du réseau d'entreprise en accélérant la fusion du réseau Cloud pour le troisième anniversaire de la licence 5G?
2022.5.28-----leetcode.1021
他26岁,发表论文18篇,刚把上世纪的素数猜想给证明了
2021年10月4日Facebook史上最严重宕机复盘分析
Machine learning - learning notes (II) - & gt; Model evaluation and selection
面试题 08.04. 幂集
Database installation --mysql
2022.5.27-----leetcode.面试17.11
What is the seven layer network structure for? Just read this article
MySQL Installer 方式安装MySQL
Yunna database monitoring tool, database monitoring operation and maintenance tool
Prototype chain? New misconceptions
com.alibaba.fastjson.JSONException: syntax error, pos 1, line 1, column 2测试
2022.5.29-----leetcode.468
selenium--显示等待(上)
Yunna | how to manage the physical assets of the company