The Maximum Subarray

  • + 0 comments

    js solution, use Kadane's algorithm for the subarray sum, however seems failing the one long test

    function maxSubarray(arr) {
        let maxSeq = pstvSum(arr)
        let min = Math.min(...arr)    
        let max = Math.max(...arr)        
        if(min>=0){
            return [maxSeq, maxSeq]     
        }else if(max<=0){
            return [max,max]
        }else{   
    		// Kadane's algorithm for subArray max sum
          return [maxSubArr(arr), maxSeq]               
        }
    
    }
    
    function pstvSum(a){
        if(a.length==0)
          return 0
        return a.reduce((tot, curr)=> {
            if(curr>0) 
              tot+=curr          
            return tot
        })
    }