Minimum Total Operations Problem
#3353
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3353.
Given an array of integers nums, you can perform any number of operations on this array.
In each operation, you can:
- Choose a prefix of the array.
- Choose an integer
k(which can be negative) and addkto each element in the chosen prefix.
A prefix of an array is a subarray that starts from the beginning of the array and extends to any point within it.
Return the minimum number of operations required to make all elements in arr equal.
Example 1:
Input: nums = [1,4,2]
Output: 2
Explanation:
- Operation 1: Choose the prefix [1, 4] of length 2 and add -2 to each element of the prefix. The array becomes [-1, 2, 2].
- Operation 2: Choose the prefix [-1] of length 1 and add 3 to it. The array becomes [2, 2, 2].
- Thus, the minimum number of required operations is 2.
Example 2:
Input: nums = [10,10,10]
Output: 0
Explanation:
- All elements are already equal, so no operations are needed.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Single Pass
We can traverse the array, and for each element, if it is not equal to the previous element, we need to perform an operation. Finally, we return the number of operations.
The time complexity is O(n), and the space complexity is O(1), where n is the length of the array.
class Solution:
def minOperations(self, nums: List[int]) -> int:
return sum(x != y for x, y in zip(nums, nums[1:]))