Minimize Array Sum Difference
Learn this problemProblem statement
Given an integer array, define its cost as the sum of absolute differences between adjacent elements: for array a of length n, cost = |a[0]-a[1]| + |a[1]-a[2]| + ... + |a[n-2]-a[n-1]|.
For example, for [5, 4, 0, 3, 3, 1] the cost is |5-4| + |4-0| + |0-3| + |3-3| + |3-1| = 10.
Remove as many elements as possible from the array so that the cost of the remaining array (computed over its new adjacent pairs) stays exactly equal to the original cost. Return the resulting array with the minimum possible number of elements.
An element can be safely removed when it does not contribute to the total cost, i.e. when its neighbors form a monotonic run through it (the absolute differences telescope). For instance, removing intermediate points along an increasing or decreasing run does not change the total.
Function
minimizeArraySumDifference(arr: int[]) → int[]Examples
Example 1
arr = [5, 4, 0, 3, 3, 1]return = [5, 0, 3, 1]
Original sum of absolute differences: |5-4|+|4-0|+|0-3|+|3-3|+|3-1| = 10.
After removing elements to minimize the array while keeping the sum the same:
Solution 1: [5, 4, 0, 3, 1] => Sum = 10
Solution 2: [5, 0, 3, 1] => Sum = 10
Solution 2 is the acceptable answer as it has the minimum number of elements.
Example 2
arr = [6, 4, 4, 3, 3, 2]return = [6, 4, 3, 2]Constraints
- The input is an array of integers.
- The cost is the sum of absolute differences of adjacent elements.
- The returned array must have exactly the same cost as the input array.
- Among all valid arrays that preserve the original cost, return one with the minimum number of elements.
- The first and last elements of the original array are always kept.
More Amazon problems
- Resolve Task DependenciesONSITE INTERVIEW · Seen Jul 2026
- Shortest Distance on a Circular Bus RouteOA · Seen Jul 2026
- Longest Increasing Subsequence With Bounded Adjacent DifferenceONSITE INTERVIEW · Seen Jul 2026
- Search in a Rotated Sorted ArrayONSITE INTERVIEW · Seen Jul 2026
- Sliding Window MaximumONSITE INTERVIEW · Seen Jul 2026
- Merge IntervalsOA · Seen Jul 2026
- Sort Bug Report FrequenciesOA · Seen Jul 2026
- Drone Delivery RouteOA · Seen Jul 2026