6

#yyds干货盘点# 解决名企真题:最大差值

 1 year ago
source link: https://blog.51cto.com/u_15488507/5446867
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 解决名企真题:最大差值

原创

97的风 2022-07-06 11:29:42 博主文章分类:面试题 ©著作权

文章标签 整型 数组 一维数组 文章分类 Java 编程语言 阅读数173

1.简述:

描述

有一个长为 n 的数组 A ,求满足 0 ≤ a ≤ b < n 的 A[b] - A[a] 的最大值。

给定数组 A 及它的大小 n ,请返回最大差值。

数据范围:  ,数组中的值满足 

示例1

[5,1],2

示例2

[5,6],2

2.代码实现:

import java.util.*;


public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A int整型一维数组
* @param n int整型
* @return int整型
*/
public int getDis (int[] A, int n) {
// write code here
int max = 0; // 结果最小为0
int min = A[0]; // 默认最小为第一位
for(int i = 1 ; i < n; i ++){
min = Math.min(A[i], min); // 第一位与遍历的比较, 取小的
max = Math.max(A[i] - min, max); // A[i]减去之前最小的A[i], 取最小的
}
return max;

}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK