LeetCode 1131: Maximum of Absolute Value Expression Solution

Master LeetCode problem 1131 (Maximum of Absolute Value Expression), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1131. Maximum of Absolute Value Expression

Medium

Problem Explanation

Explanation

To find the maximum value of the given expression, we need to consider all pairs of indices (i, j) and calculate the absolute difference between the corresponding elements in both arrays along with the absolute difference of the indices. We can simplify this by breaking down the expression into four parts:

  1. arr1[i] + arr2[i] + i
  2. arr1[i] - arr2[i] + i
  3. arr1[i] + arr2[i] - i
  4. arr1[i] - arr2[i] - i

For each of the above parts, we need to find the maximum difference between the maximum and minimum values obtained for all elements in the arrays.

Solution Code

class Solution {
    public int maxAbsValExpr(int[] arr1, int[] arr2) {
        int n = arr1.length;
        int max1 = Integer.MIN_VALUE, min1 = Integer.MAX_VALUE;
        int max2 = Integer.MIN_VALUE, min2 = Integer.MAX_VALUE;
        int max3 = Integer.MIN_VALUE, min3 = Integer.MAX_VALUE;
        int max4 = Integer.MIN_VALUE, min4 = Integer.MAX_VALUE;

        for (int i = 0; i < n; i++) {
            max1 = Math.max(max1, arr1[i] + arr2[i] + i);
            min1 = Math.min(min1, arr1[i] + arr2[i] + i);

            max2 = Math.max(max2, arr1[i] - arr2[i] + i);
            min2 = Math.min(min2, arr1[i] - arr2[i] + i);

            max3 = Math.max(max3, arr1[i] + arr2[i] - i);
            min3 = Math.min(min3, arr1[i] + arr2[i] - i);

            max4 = Math.max(max4, arr1[i] - arr2[i] - i);
            min4 = Math.min(min4, arr1[i] - arr2[i] - i);
        }

        return Math.max(Math.max(max1 - min1, max2 - min2), Math.max(max3 - min3, max4 - min4));
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1131 (Maximum of Absolute Value Expression)?

This page provides optimized solutions for LeetCode problem 1131 (Maximum of Absolute Value Expression) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1131 (Maximum of Absolute Value Expression)?

The time complexity for LeetCode 1131 (Maximum of Absolute Value Expression) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1131 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1131 in Java, C++, or Python.

Back to LeetCode Solutions