Problem · Dynamic Programming
Modify Array
Learn this problemProblem statement
Given an array of integers, the cost to change an element is the absolute difference between its initial value and its new value. For example, if the element is initially 10, it can be changed to 7 or 13 for a cost of 3. Determine the minimum cost to sort the array either ascending or descending along its length.
Function
modifyArray(arr: int[]) → int
Complete the function modifyArray in the editor.
modifyArray has the following parameters:
int arr[n]: an array of integers
Returns
int: an integer that denotes the minimum cost required to make the array ascending (non-decreasing) or descending (non-increasing) along its length.
Examples
Example 1
arr = [9, 8, 7, 2, 3, 3]return = 1N/A :)
Example 2
arr = [1, 2, 3, 3, 4]return = 0The array arr is already sorted in ascending order.
The minimum cost to sort it in ascending order is 0.
Example 3
arr = [0, 1, 2, 5, 6, 5, 7]return = 1Only arr[5] = 5 violates the order for an ascending sort.
If the value 5 is increased to 6, the arr will be sorted in ascending order: arr' = [0, 1, 2, 5, 6, 6, 7]
The cost is |arr[5] - [5 - 6]| = 1 :)