Find minimum total range-increment to sort
AmazonSoftware Engineer · Online AssessmentLast updated
This problem tests your ability to determine the minimum total operations required to make an array non-decreasing by incrementing contiguous subarrays, requiring insights into difference arrays or monotonic properties.
Problem Statement
You are given an array arr of n integers. You can perform an operation: choose a range [i, j] (inclusive) and increment all elements in that range by 1. Each operation costs 1 unit. Your goal is to find the minimum number of operations required to make the array sorted in non-decreasing order (i.e., arr[i] int:
Constraints
1 <= n <= 10^50 <= arr[i] <= 10^9
Examples
Example 1:
Input: arr = [3, 2, 1]
Output: 2
Explanation:
- Increment
[1, 2]to get[3, 3, 2]. - Increment
[2, 2]to get[3, 3, 3]. Alternatively, identify the required differences:d[i] = arr[i] - arr[i-1]. Ifd[i] < 0, we need to cover the deficiency.
Example 2:
Input: arr = [1, 2, 3]
Output: 0
Explanation: The array is already sorted.
Edge Cases
- Array with 1 element: Output should be 0.
- Array with all identical elements: Output should be 0.
- Strictly decreasing array: The algorithm must handle the cumulative needs.
Hints
Hint 1
Consider the difference array `diff[i] = arr[i] - arr[i-1]` for `i > 0`.
Hint 2
The condition `arr[i] >= arr[i-1]` is equivalent to `arr[i] - arr[i-1] >= 0`.
Hint 3
If `arr[i] < arr[i-1]`, you have a 'deficit' that must be corrected by increments applied to the suffix starting at index `i`.
Follow-up questions
- How does the complexity change if you are allowed to increment or decrement the range?
- What if the cost of an operation is not 1, but proportional to the length of the range `(j - i + 1)`?
- Can you solve this problem if you are only allowed to perform operations on a fixed-length window of size `k`?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.