java面試寶典page279 求數對之差的最大值(動態規劃)
阿新 • • 發佈:2018-11-03
package com.interview.datastructure; public class TestDynamicProgramming { //java面試寶典page279 求數對之差的最大值 //1.首先定義一個max方法來判斷儲存最大值 //2.如何構造動態規劃,如果原來的n個數中不是最大值,需要更新,那麼更新的最大值必然是原來n個數中的最大值-第n+1個數; public static int max(int m, int n) { return (m > n) ? m : n; } public static int getMax(int[] a) { int diff[] = new int[a.length]; int max[] = new int[a.length]; max[0] = a[0]; diff[0] = Integer.MIN_VALUE; for (int i = 1; i < a.length; i++) { diff[i] = max(diff[i - 1], max[i - 1] - a[i]); max[i] = max(max[i - 1], a[i]); } return diff[a.length - 1]; } public static void main(String[] args) { int[] a = {5, 6, 9, 8, 7, 51, 2, -6}; System.out.println(getMax(a)); }}