LeetCode: Minimum Number Of Operations To Move All Balls To Each Box Solution
1/**2 * @param {string} boxes3 * @return {number[]}4 */5var minOperations = function (boxes) {6 boxes = boxes.split("").map(Number)7 const ones = boxes8 .map((el, i) => [el, i])9 .filter(([el]) => el === 1)10 .map(([_, i]) => i)1112 const res = Array.from({ length: boxes.length }, (_, i) =>13 ones.reduce((acc, oneIdx) => (acc += Math.abs(i - oneIdx)), 0)14 )15 return res16}
Comments
Loading comments...
Tags
leetcode
array
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.