Loading

左侧数组最大值减去右侧数组最大值的最大绝对值

 

package com.srie.test;


public class Test02 {

    public int sol(int[] nums) {
        if (nums == null || nums.length == 0 || nums.length == 1) {
            return 0;
        }
        int n = nums.length;
        // store the right max in an array;
        int rightmax[] = new int[n];

        rightmax[n - 1] = nums[n - 1]; // just save the last element; 
        int max = nums[n - 1];
        for (int i = n - 2; i >= 0; --i) {
            max = Math.max(nums[i], max); 
            rightmax[i] = Math.max(rightmax[i + 1], max); // store the max element;
        }
        // System.out.println(Arrays.toString(rightmax));

        // left max element
        int leftmax = nums[0];
        int res = Math.abs(leftmax - rightmax[1]);

        for (int i = 1; i < n - 1; i++) {
            leftmax = nums[i];
            res = Math.max(res, Math.abs(leftmax - rightmax[i + 1]));
        }
        return res;
    }

    public static void main(String[] args) {
        int[] a = { 1, 2, 4, 8 };
        Test02 t02 = new Test02();
        int i = t02.sol(a);
        System.out.println(i);
        int[] b = { 1, 3, -3 };
        System.out.println(t02.sol(b));
        // maxmaxdifference
        // bugfixingCoins
    }

}

 

posted @ 2017-02-22 20:15  stono  阅读(552)  评论(0编辑  收藏  举报