Leetcode 1131: Maximum of Absolute Value Expression

grid47
grid47
Exploring patterns and algorithms
Jul 16, 2024 5 min read

You are given two arrays arr1 and arr2 of integers, both having equal lengths. Calculate the maximum value of the expression: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| for all pairs of indices i and j, where 0 <= i, j < arr1.length.
Problem
Approach
Steps
Complexity
Input: You are given two arrays arr1 and arr2 of integers of equal length.
Example: Input: arr1 = [3, 1, 4, 5], arr2 = [2, 0, 3, 4]
Constraints:
• 2 <= arr1.length == arr2.length <= 40000
• -10^6 <= arr1[i], arr2[i] <= 10^6
Output: Return the maximum value of the expression: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|.
Example: Output: 9
Constraints:
• The answer fits within a 32-bit signed integer.
Goal: The goal is to compute the maximum value of the expression |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| for all pairs of indices.
Steps:
• Iterate through the array using nested loops for indices i and j.
• For each pair of indices, calculate the expression value and update the result if it's larger than the current maximum value.
Goal: Ensure the solution handles arrays of large sizes and values efficiently.
Steps:
• The array lengths must be between 2 and 40,000.
• The values of arr1 and arr2 are within the range [-10^6, 10^6].
Assumptions:
• The arrays are guaranteed to have the same length, and there will always be at least two elements.
Input: Input: arr1 = [3, 1, 4, 5], arr2 = [2, 0, 3, 4]
Explanation: For this example, the maximum value of the expression occurs at indices i = 0 and j = 3. The value of the expression is 9.

Input: Input: arr1 = [1, -2, 3], arr2 = [0, 2, 1]
Explanation: For this example, the maximum value occurs at indices i = 0 and j = 2. The value of the expression is 8.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus