Find the Minimum Shared Increment on Nonadjacent Array Positions
Company: IBM
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Online Assessment
Overview: Choose nonadjacent indices for one common nonnegative increment to make an array nondecreasing, or determine that no operation can succeed.
Constraints
- 0 <= len(values) <= 200000
- -1000000000 <= values[i] <= 1000000000
- x is an integer, must be nonnegative, and has no additional artificial upper bound
- Chosen indices are pairwise nonadjacent: no two chosen indices differ by one, and the same x is added at every chosen index
- Unchosen elements do not change, and there is no requirement to choose any index
- Return 0 when the array is already nondecreasing, including the empty array and any one-element array
- Do not mutate the input array
- The answer can reach 2000000000 and values[i] + x can reach 3000000000, which exceeds 2^31 - 1, so use 64-bit integers (long in Java, long long in C++)
Examples
Input: ([],)
Expected Output: 0
Explanation: The empty array is nondecreasing by the stated boundary convention, so no operation is needed.
Input: ([7],)
Expected Output: 0
Explanation: A one-element array is nondecreasing by the stated boundary convention.
Hints
- Consider one adjacent pair at a time and remember that its two positions can never both be chosen, so a pair admits only three situations: neither position raised, the left one raised, or the right one raised.
- When values[i] > values[i + 1], ask which of the two positions could possibly be raised given that x is nonnegative; the answer leaves you no freedom at either position.
- Each adjacent pair turns into either a lower bound or an upper bound on the single shared x; the operation exists only when all of those bounds can hold simultaneously.