#3353
Easy Algorithms Minimum total operations
Array
63.8% acceptance
Mar 31, 2026
14
1
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 add k to 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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_operations(nums: Vec<i32>) -> i32 {
// Each prefix operation can change a difference between consecutive elements.
// The number of operations = number of i where nums[i] != nums[i+1].
let mut count = 0;
for i in 1..nums.len() {
if nums[i] != nums[i - 1] {
count += 1;
}
}
count
}
}