Input: nums =[3,9,7], k =5Output: 4Explanation:
* Perform 4 operations on `nums[1] = 9`. Now,`nums = [3, 5, 7]`.* The sum is15, which is divisible by 5.
Input: nums =[3,2], k =6Output: 5Explanation:
* Perform 3 operations on `nums[0] = 3` and 2 operations on `nums[1] = 2`. Now,`nums = [0, 0]`.* The sum is0, which is divisible by 6.
To make the sum divisible by k, we need to reduce the sum by its remainder modulo k. The minimum number of operations is equal to the remainder, and we can perform all operations on any element as long as it is large enough.
classSolution {
public:int minOperations(vector<int>& nums, int k) {
int sum = accumulate(nums.begin(), nums.end(), 0);
int rem = sum % k;
return rem ==0?0: rem;
}
};
classSolution {
publicintminOperations(int[] nums, int k) {
int sum = 0;
for (int v : nums) sum += v;
int rem = sum % k;
return rem == 0 ? 0 : rem;
}
}
1
2
3
4
5
6
7
classSolution {
funminOperations(nums: IntArray, k: Int): Int {
val sum = nums.sum()
val rem = sum % k
returnif (rem ==0) 0else rem
}
}
1
2
3
4
classSolution:
defminOperations(self, nums: list[int], k: int) -> int:
rem: int = sum(nums) % k
return0if rem ==0else rem
1
2
3
4
5
6
7
impl Solution {
pubfnmin_operations(nums: Vec<i32>, k: i32) -> i32 {
let sum: i32= nums.iter().sum();
let rem = sum % k;
if rem ==0 { 0 } else { rem }
}
}
To make the sum divisible by k, we need to reduce the sum by its remainder modulo k. The minimum number of operations is equal to the remainder, and we can perform all operations on any element as long as it is large enough.
classSolution {
public:int minOperations(vector<int>& nums, int k) {
int sum = accumulate(nums.begin(), nums.end(), 0);
int rem = sum % k;
return rem ==0?0: rem;
}
};
classSolution {
publicintminOperations(int[] nums, int k) {
int sum = 0;
for (int v : nums) sum += v;
int rem = sum % k;
return rem == 0 ? 0 : rem;
}
}
1
2
3
4
5
6
7
classSolution {
funminOperations(nums: IntArray, k: Int): Int {
val sum = nums.sum()
val rem = sum % k
returnif (rem ==0) 0else rem
}
}
1
2
3
4
classSolution:
defminOperations(self, nums: list[int], k: int) -> int:
rem = sum(nums) % k
return0if rem ==0else rem
1
2
3
4
5
6
7
impl Solution {
pubfnmin_operations(nums: Vec<i32>, k: i32) -> i32 {
let sum: i32= nums.iter().sum();
let rem = sum % k;
if rem ==0 { 0 } else { rem }
}
}