LeetCode: Partition Array into Disjoint Intervals Solution

Reasoning

Approach

LeetCode's official solution covered well

Implementation

1/**
2 * @param {number[]} nums
3 * @return {number}
4 */
5var partitionDisjoint = function (nums) {
6 const [prefixMax, postfixMin] = [[], []]
7 let [max, min] = [nums[0], nums.slice(-1)[0]]
8
9 for (const num of nums) {
10 max = Math.max(max, num)
11 prefixMax.push(max)
12 }
13
14 for (const num of [...nums].reverse()) {
15 min = Math.min(min, num)
16 postfixMin.push(min)
17 }
18 postfixMin.reverse()
19
20 for (let i = 0; i < nums.length - 1; i++) {
21 if (prefixMax[i] <= postfixMin[i + 1]) {
22 return i + 1
23 }
24 }
25
26 return 0
27}

Comments

Loading comments...

Tags

leetcode

array

Next Post

LeetCode: Palindrome Number

Jul 22, 2021

Split, reverse, join

Previous Post

LeetCode: Shuffle an Array

Jul 21, 2021

Fisher–Yates shuffle

HoningJS

Search Posts