求数组中数对之差的最大值

数组中的一个数字减去它右边子数组中的一个数字可以得到一个差值,求所有可能的差值中的最大值,例如,数组{1,4,17,3,2,9}中,最大的差值为17-2 =15。

动态规划法:

我们用变量dif来记录前i+1个数组成的序列的最大数对差。
用变量max来记录前i+1个数的最大值。
那么对于i+1来说,dif=两者最大值{dif,max-a[i+1]}
迭代到最后,dif就储存了最大的数对之差。

	public static int method(int[] a) {
		if (a == null)
			return Integer.MIN_VALUE;
		if (a.length == 1)
			return Integer.MIN_VALUE;
		int dif = a[0] - a[1];
		int max = a[0] > a[1] ? a[0] : a[1];
		for (int i = 2; i < a.length; i++) {
			max = max > a[i] ? max : a[i];
			dif = dif > (max - a[i]) ? dif : (max - a[i]);
		}

		return dif;
	}

	public static void main(String[] args) {
		int[] a = { 1, 4, 17, 3, 2, 9 };
		System.out.println(method(a));//15
	}
发布了58 篇原创文章 · 获赞 0 · 访问量 978

猜你喜欢

转载自blog.csdn.net/Mason97/article/details/104565929
今日推荐