Problem · Array
Array Challenge (QR Intern)
Learn this problemProblem statement
You are given an integer array arr.
For each element arr[i]:
- Initialize a counter to
0. - Compare
arr[i]with every elementarr[j]to its left, wherej < i.- If
arr[j] > arr[i], subtract|arr[i] - arr[j]|from the counter. - If
arr[j] < arr[i], add|arr[i] - arr[j]|to the counter. - If the two values are equal, the counter does not change.
- If
Return a new array containing the final counter value for each element.
Function
arrayChallenge(arr: int[]) → int[]Examples
Example 1
arr = [2,4,3]return = [0,2,0]- For
arr[0] = 2, there are no elements to the left, so the counter is0. - For
arr[1] = 4, add|4 - 2| = 2, so the counter is2. - For
arr[2] = 3, first compare with4:0 - |3 - 4| = -1. Then compare with2:-1 + |3 - 2| = 0.
Therefore, return [0, 2, 0].
Constraints
1 <= arr.length <= 10^5.