The Maximum Subarray

  • + 0 comments

    JS

    function maxSubarray(array) {
        const getMaxSubsum = array => {
            let maxSum = -Infinity;
            array.reduce((sum, value) => {
                sum += value;
                maxSum = Math.max(maxSum, sum);
                return (sum > 0) ? sum : 0;
            }, 0);
            return maxSum;
        };
        const getMaxSubsequence = array => {
            array.sort((a, b) => a - b);
            return (array.at(-1) < 0) ? array.at(-1) : array.filter(value => value >= 0).reduce((sum, value) => sum + value);
        };
        return [getMaxSubsum(array), getMaxSubsequence(array)];
    }