LeetCode: Equal Sum Arrays With Minimum Number Of Operations Solution

Approach

store the array of changes

• with array of larger sum, calculate the change to 1 for each
• with array of smaller sum, calculate the change to 6 for each

sort the change desc, decrease the init sum diff between two arrays

Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} nums13 * @param {number[]} nums24 * @return {number}5 */6var minOperations = function (nums1, nums2) {7  const sum = arr => arr.reduce((acc, el) => acc + el, 0)8
9  let largerSumArr, smallerSumArr10  if (sum(nums1) > sum(nums2)) {11    largerSumArr = [...nums1]12    smallerSumArr = [...nums2]13  } else {14    largerSumArr = [...nums2]15    smallerSumArr = [...nums1]16  }17
18  let res = 019  let diff = sum(largerSumArr) - sum(smallerSumArr)20
21  if (diff === 0) {22    return 023  }24
25  let changes = [26    ...largerSumArr.map(el => el - 1),27    ...smallerSumArr.map(el => 6 - el),28  ].sort((a, b) => b - a)29
30  for (const change of changes) {31    res++32    diff -= change33    if (diff <= 0) return res34  }35
36  return -137}```

leetcode

greedy

Next Post

LeetCode: Closest Dessert Cost

Feb 28, 2021

Search Posts