Split Array Largest Sum

https://leetcode.com/problems/split-array-largest-sum/?tab=Description

class Solution {
public:
    int splitArray(vector<int>& nums, int m) {
        int maxnumber = 0;
        long sum = 0;
        for(int num : nums)
        {
            maxnumber = max(num, maxnumber);
            sum += num;
        }
        if(m == 1)
        {
            return sum;
        }

        long l = maxnumber;
        long r = sum;
        while(l <= r)
        {
            long mid = (l+r)/2;
            if(valid(mid, nums, m))
            {
                r = mid-1;
            }
            else
            {
                l = mid+1;
            }
        }

        return (int)l;
    }

    bool valid(long target, vector<int>& nums, int m)
    {
        int count = 1;
        int total = 0;
        for(int num : nums)
        {
            total += num;
            if(total > target)
            {
                total = num;
                count++;
                if(count > m)
                {
                    return false;
                }
            }
        }
        return true;
    }
};

results matching ""

    No results matching ""