DEV Community

codingpineapple
codingpineapple

Posted on

2 2

LeetCode 410. Split Array Largest Sum (javascript solution)

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
};
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay