Input: nums =[1,4,2]Output: 2Explanation:
***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 is2.
Example 2:
1
2
3
4
Input: nums =[10,10,10]Output: 0Explanation:
* All elements are already equal, so no operations are needed.
To make all elements equal, we need to eliminate every change in value as we scan from left to right. Each time the value changes, we need an operation to adjust the prefix so the next value matches the previous ones.
classSolution {
public:int minimumOperations(vector<int>& nums) {
int ops =0;
for (int i =1; i < nums.size(); ++i) {
if (nums[i] != nums[i-1]) ++ops;
}
return ops;
}
};
1
2
3
4
5
6
7
8
9
funcMinimumOperations(nums []int) int {
ops:=0fori:=1; i < len(nums); i++ {
ifnums[i] !=nums[i-1] {
ops++ }
}
returnops}
1
2
3
4
5
6
7
8
9
classSolution {
publicintminimumOperations(int[] nums) {
int ops = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i]!= nums[i-1]) ops++;
}
return ops;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funminimumOperations(nums: IntArray): Int {
var ops = 0for (i in1 until nums.size) {
if (nums[i] != nums[i-1]) ops++ }
return ops
}
}
1
2
3
4
5
6
7
8
from typing import List
classSolution:
defminimumOperations(self, nums: List[int]) -> int:
ops =0for i in range(1, len(nums)):
if nums[i] != nums[i-1]:
ops +=1return ops
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnminimum_operations(nums: Vec<i32>) -> i32 {
letmut ops =0;
for i in1..nums.len() {
if nums[i] != nums[i-1] {
ops +=1;
}
}
ops
}
}
1
2
3
4
5
6
7
8
9
classSolution {
minimumOperations(nums: number[]):number {
letops=0;
for (leti=1; i<nums.length; i++) {
if (nums[i] !==nums[i-1]) ops++;
}
returnops;
}
}