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[]} nums13 * @param {number[]} nums24 * @return {number}5 */6var minOperations = function (nums1, nums2) {7 const sum = arr => arr.reduce((acc, el) => acc + el, 0)89 let largerSumArr, smallerSumArr10 if (sum(nums1) > sum(nums2)) {11 largerSumArr = [...nums1]12 smallerSumArr = [...nums2]13 } else {14 largerSumArr = [...nums2]15 smallerSumArr = [...nums1]16 }1718 let res = 019 let diff = sum(largerSumArr) - sum(smallerSumArr)2021 if (diff === 0) {22 return 023 }2425 let changes = [26 ...largerSumArr.map(el => el - 1),27 ...smallerSumArr.map(el => 6 - el),28 ].sort((a, b) => b - a)2930 for (const change of changes) {31 res++32 diff -= change33 if (diff <= 0) return res34 }3536 return -137}
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.