JAVA程序设计:绝对值表达式的最大值(LeetCode:1131)

给你两个长度相等的整数数组,返回下面表达式的最大值:

|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|

其中下标 i,j 满足 0 <= i, j < arr1.length。

 

示例 1:

输入:arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
输出:13
示例 2:

输入:arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
输出:20
 

提示:

2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6

思路:一般遇到这种问题,我们应该想着去掉绝对值试试看,由于绝对值中相减的数并不确定大小,因此肯定是要分情况讨论的,但是一般不会很复杂,这里我不再过多赘述,可以参考一篇讲解很棒的题解。

class Solution {
    public int maxAbsValExpr(int[] arr1, int[] arr2) {

        int len = arr1.length;
        int a_min = Integer.MAX_VALUE, a_max = Integer.MIN_VALUE;
        int b_min = Integer.MAX_VALUE, b_max = Integer.MIN_VALUE;
        int c_min = Integer.MAX_VALUE, c_max = Integer.MIN_VALUE;
        int d_min = Integer.MAX_VALUE, d_max = Integer.MIN_VALUE;

        for (int i = 0; i < len; i++) {
            a_min = Math.min(a_min, arr1[i] + arr2[i] + i);
            a_max = Math.max(a_max, arr1[i] + arr2[i] + i);
            b_min = Math.min(b_min, arr1[i] + arr2[i] - i);
            b_max = Math.max(b_max, arr1[i] + arr2[i] - i);
            c_min = Math.min(c_min, arr1[i] - arr2[i] + i);
            c_max = Math.max(c_max, arr1[i] - arr2[i] + i);
            d_min = Math.min(d_min, arr1[i] - arr2[i] - i);
            d_max = Math.max(d_max, arr1[i] - arr2[i] - i);
        }
        
        int a = Math.max(a_max - a_min, b_max - b_min);
        int b = Math.max(c_max - c_min, d_max - d_min);

        return Math.max(a, b);

    }
}

 

你可能感兴趣的:(JAVA程序设计:绝对值表达式的最大值(LeetCode:1131))