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

1/**
2 * @param {number[]} nums1
3 * @param {number[]} nums2
4 * @return {number}
5 */
6var minOperations = function (nums1, nums2) {
7 const sum = arr => arr.reduce((acc, el) => acc + el, 0)
8
9 let largerSumArr, smallerSumArr
10 if (sum(nums1) > sum(nums2)) {
11 largerSumArr = [...nums1]
12 smallerSumArr = [...nums2]
13 } else {
14 largerSumArr = [...nums2]
15 smallerSumArr = [...nums1]
16 }
17
18 let res = 0
19 let diff = sum(largerSumArr) - sum(smallerSumArr)
20
21 if (diff === 0) {
22 return 0
23 }
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 -= change
33 if (diff <= 0) return res
34 }
35
36 return -1
37}

Comments

Loading comments...

Tags

leetcode

greedy

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Closest Dessert Cost

Feb 28, 2021

Previous Post

HoningJS

Search Posts