Description
Solutions
Modify Array
📚RELATED PROBLEMS
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 Description
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.
Example 1:
Input: arr = [9, 8, 7, 2, 3, 3]
Output: 1
Explanation:N/A :)
Example 2:
Input: arr = [1, 2, 3, 3, 4]
Output: 0
Explanation:The array arr is already sorted in ascending order. The minimum cost to sort it in ascending order is 0.
Example 3:
Input: arr = [0, 1, 2, 5, 6, 5, 7]
Output: 1
Explanation:Only 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 :)
Constraints:
- 1 ≤ n ≤ 10^3
- 1 ≤ arr[i] ≤ 10^9

Related Problems
Testcase
Result
Case 1
input:
output: