码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-30 00:25:56      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:

一道面试题:对于无序数组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 }

 

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

标签:

原文地址:http://www.cnblogs.com/freedom-wangyb/p/4192611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!