Problem · Array
Array Challenge
For each element in an array, implement a function that:
- Initializes a counter to
0for each element. - Compares the element with each element to its left:
- If the left element is greater, subtract the absolute difference from the counter.
- If the left element is smaller, add the absolute difference to the counter.
- Returns a new array containing the final counter values for each element.
Complete the function arrayChallenge in the editor with the following parameter:
int arr[n]: an array of integers
Returns
int[n]: an array of integers calculated as described
Examples
01 · Example 1
arr = [2, 4, 3] return = [0, 2, 0]
- For
arr[0] = 2, counter starts at0, and there are no elements to the left, so the counter is0. - For
arr[1] = 4, counter starts at0and then increases by|4 - 2| = 2at the first and only comparison; counter =2. - Testing
arr[2] = 3, first against4, counter =0 - |3 - 4| = -1, and then against2, counter =-1 + |3 - 2| = 0. - The answer array is
[0, 2, 0].
02 · Example 2
arr = [2, 1, 3] return = [0, -1, 3]
The first element has none to its left, so counter = 0.
The second element, counter = 0 - |1 - 2| = -1.
The third element, counter = 0 + |3 - 1| + |3 - 2| = 3.
Constraints
1 <= n <= 10^51 <= arr[i] <= 10^9
More JPMorgan Chase problems
public int[] arrayChallenge(int[] arr) {
// write your code here
}arr[2, 4, 3]
expected[0, 2, 0]
checking account