问题:
数组中的一个数字减去它右边子数组中的一个数字可以得到一个差值,求所有可能的差值中的最大值,例如,数组{1,4,17,3,2,9}中,最大差值为17-2=15。
方法一:
暴力法。双重循环遍历数组,寻找任意两个元素之间的差值,并取最大值。时间复杂度:O(n)
方法一代码如下:
package com.haobi;
/*
* 方法一:暴力法。
*/
public class Test18 {
public static void main(String[] args) {
int[] a = {1,4,17,3,2,9};
System.out.println(getMax(a));
}
public static int getMax(int[] a) {
if(a == null) {
return Integer.MAX_VALUE;
}
int len = a.length;
if(len<=1) {
return Integer.MIN_VALUE;
}
//定义变量存储最大值
int max = Integer.MIN_VALUE;
//双重循环
for(int i=0;i<len-1;i++) {
for(int j=i+1;j<len;j++) {
if(a[i] - a[j] > max) {
max = a[i] - a[j];
}
}
}
return max;
}
}
程序输出结果如下:
15
方法二:
分治法/递归法。把数组分为两个子数组