标签:
一道面试题:对于无序数组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 }
标签:
原文地址:http://www.cnblogs.com/freedom-wangyb/p/4192611.html