2541. Minimum Operations to Make Array Equal II
2023. 1. 29. 17:29ㆍAlgorithm/Leetcode, Lintcode, HackerRank, etc.
- 목차
반응형
two arrays and integer value k are provided.
the thing you need to do is to figure out the minumum number of changes by applying operation.
the operation is as follows.
- in the first array, nums1
- pick two indices i, j
- apply nums1[i] + k, nums1[j] - k
- and check the nums1 and the nums2 are equal, if so, then return the number of operations until then.
Python
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int:
is_diff = False
for i in range(len(nums1)):
if nums1[i] != nums2[i]:
is_diff = True
break
else:
return 0
if is_diff and k == 0:
return -1
pos = 0
neg = 0
for i in range(len(nums1)):
diff = nums1[i] - nums2[i]
if diff >= 0:
pos += diff
else:
neg += diff
if diff % k != 0:
return -1
if pos != abs(neg):
return -1
return pos//k
import kotlin.math.abs
class Solution {
fun minOperations(nums1: IntArray, nums2: IntArray, k: Int): Long {
var is_diff: Boolean = false
for (i in 0 until nums1.size) {
if (nums1[i] != nums2[i]) {
is_diff = true
break
}
}
if (is_diff == false && k == 0) {
return 0
}
if (is_diff && k == 0) {
return -1
}
var pos: Long = 0
var neg: Long = 0
for (i in 0 until nums1.size) {
var diff = nums1[i] - nums2[i]
if (diff >= 0) {
pos += diff
} else {
neg += diff
}
if (diff % k != 0) {
return -1
}
}
if (pos != abs(neg)) {
return -1
}
return (pos.toDouble() / k.toDouble()).toLong()
}
}
반응형
'Algorithm > Leetcode, Lintcode, HackerRank, etc.' 카테고리의 다른 글
3100. Water Bottles II (0) | 2024.04.05 |
---|---|
2717. Semi-Ordered Permutation (0) | 2023.06.05 |
2545. Sort the Students by Their Kth Score (0) | 2023.01.29 |
2544. Alternating Digit Sum (0) | 2023.01.28 |
2255. Count Prefixes of a Given String (0) | 2023.01.26 |