LeetCode: Array Partition I Solution

Sometimes, don't analyse

Approach

Greedily make pairs of smallest and next smallest numbers

Sort array for easy iteration

Why? Let's take this sorted array

11 2 3 4

If we pair 1 with 3, will miss 3 as min in a pair

Implementation

1var arrayPairSum = function (nums) {
2 return nums
3 .sort((a, b) => (a < b ? -1 : 1))
4 .filter((_, index) => index % 2 === 0)
5 .reduce((sum, num) => sum + num, 0)
6}

Comments

Loading comments...

Tags

leetcode

array

sorting

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: Keyboard Row

Duck-typing make this problem less hard to implement

Previous Post

LeetCode: Maximum Product of Three Numbers

Sort and keep in mind of negative numbers

HoningJS

Search Posts