LeetCode 410. Split Array Largest Sum (javascript solution)
codingpineapple
Posted on May 13, 2021
Description:
Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these m subarrays.
Solution:
Time Complexity : O(nlog(n))
Space Complexity: O(1)
// Binary Search approach
var splitArray = function(nums, m) {
// Check if the passed in threshold can be the max sum of the subarrays
function checkIsFeasable (threshold) {
let count = 1
let total = 0
for (const num of nums){
total += num
if (total > threshold){
total = num
count += 1
if (count > m){
return false
}
}
}
return true
}
// Binary search template
let left = Math.max(...nums), right = nums.reduce((all, item) => all+item)
while(left < right) {
const mid = left + Math.floor((right-left)/2)
if(checkIsFeasable(mid)) {
right = mid
} else {
left = mid + 1
}
}
return left
};
π πͺ π
π©
codingpineapple
Posted on May 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
sorting Recap the highlight of the sorting algorithms using JavaScript for beginners
October 5, 2024
datastructures DSA with JS: Understanding Custom Array Data Structure in JavaScript - A Step-by-Step Guide
September 29, 2024