无序数组a,求a[i]-a[j]的最大值,且i<j

一道面试题:对于无序数组a,求a[i]-a[j]的最大值,其中i<j


 

 1 package test;
 2 
 3 import java.util.Arrays;
 4 
 5 public class FindMax {
 6     public static void main(String[] args) {
 7         int[] a = new int[] { 9, 20, 3, 16, 6, 5, 7, 1 };
 8         System.out.println("a[" + a.length + "]=" + Arrays.toString(a));
 9         System.out.println("find max of a[i]-a[j],i<j : " + findMax(a));
10     }
11 
12     public static int findMax(int[] a) {
13         // 初始化为最小可能的int值
14         int max = Integer.MIN_VALUE;
15         // a[i]右边元素中的最小值
16         int minRight = a[a.length - 1];
17         int tempMax;
18         for (int i = a.length - 2; i >= 0; i--) {
19             tempMax = a[i] - minRight;
20             if (a[i] < minRight) {
21                 minRight = a[i];
22             }
23             if (tempMax > max) {
24                 max = tempMax;
25             }
26         }
27         return max;
28     }
29 }

 

转载于:https://www.cnblogs.com/freedom-wangyb/p/4192611.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值