Input: nums =[1,2,3], target =[4]Output: 1Explanation:
The minimum number of operations required to satisfy the condition is1.* Increment 3 to 4with just one operation, making 4 a multiple of itself.
Input: nums =[8,4], target =[10,5]Output: 2Explanation:
The minimum number of operations required to satisfy the condition is2.* Increment 8 to 10with2 operations, making 10 a multiple of both 5 and 10.
For each target value, we need at least one number in nums that is a multiple of it. For each target, find the closest multiple in nums (possibly after increments) and sum the required increments. We can use a mapping from each target to the minimum increment needed.
classSolution {
public:int minOperations(vector<int>& nums, vector<int>& target) {
int ans =0;
for (int t : target) {
int mn = INT_MAX;
for (int x : nums) {
int need = (x >= t) ? (x % t ==0?0: t - x % t) : t - x;
mn = min(mn, need);
}
ans += mn;
}
return ans;
}
};
funcminOperations(nums []int, target []int) int {
ans:=0for_, t:=rangetarget {
mn:=1<<30for_, x:=rangenums {
varneedintifx>=t {
ifx%t==0 {
need = 0 } else {
need = t-x%t }
} else {
need = t-x }
ifneed < mn {
mn = need }
}
ans+=mn }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintminOperations(int[] nums, int[] target) {
int ans = 0;
for (int t : target) {
int mn = Integer.MAX_VALUE;
for (int x : nums) {
int need = x >= t ? (x % t == 0 ? 0 : t - x % t) : t - x;
mn = Math.min(mn, need);
}
ans += mn;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funminOperations(nums: IntArray, target: IntArray): Int {
var ans = 0for (t in target) {
var mn = Int.MAX_VALUE
for (x in nums) {
val need = if (x >= t) if (x % t ==0) 0else t - x % t else t - x
mn = minOf(mn, need)
}
ans += mn
}
return ans
}
}
1
2
3
4
5
6
7
8
9
defmin_operations(nums: list[int], target: list[int]) -> int:
ans =0for t in target:
mn = float('inf')
for x in nums:
need = (x >= t) and (x % t ==0) and0or (x >= t) and (t - x % t) or (t - x)
mn = min(mn, need)
ans += mn
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnmin_operations(nums: Vec<i32>, target: Vec<i32>) -> i32 {
letmut ans =0;
for&t in&target {
letmut mn =i32::MAX;
for&x in&nums {
let need =if x >= t {
if x % t ==0 { 0 } else { t - x % t }
} else {
t - x
};
mn = mn.min(need);
}
ans += mn;
}
ans
}
}