4124. Minimum Operations to Make Mountain Array II π
DifficultyHard
Description
You are given an integer array nums of length n.
In one operation, you may increment or decrement any element of nums by 1. Elements are not required to stay positive.
An array is called a mountain array if there exists an index peak such that 0 < peak < n - 1 and:
nums[0] < nums[1] < ... < nums[peak]nums[peak] > nums[peak + 1] > ... > nums[n - 1]
Return the minimum number of operations required to transform nums into a mountain array. If it is impossible, return -1.
Example 1:
Input: nums = [2,2,3]
Output: 2
Explanation:
One optimal way is to:
- Increment
nums[1]by 1 and decrementnums[2]by 1. - The resulting array is
[2, 3, 2], which is a mountain array withpeak = 1. - Therefore, the total number of operations is
1 + 1 = 2.
Example 2:
Input: nums = [3,1,2,5,4]
Output: 3
Explanation:
One optimal way is to:
- Decrement
nums[0]by 1 three times, making it 0. - The resulting array is
[0, 1, 2, 5, 4], which is a mountain array withpeak = 3. - Therefore, the total number of operations is 3.
Example 3:
Input: nums = [5,7,7,4]
Output: 1
Explanation:
One optimal way is to:
- Decrement
nums[1]by 1. - The resulting array is
[5, 6, 7, 4], which is a mountain array withpeak = 2. - Therefore, the total number of operations is 1.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 105
Solutions
Solution 1
1 | |
1 | |
1 | |
1 | |