2541. Minimum Operations to Make Array Equal II

2023. 1. 29. 17:29Algorithm/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()
    }
}
반응형