The Maximum Subarray

Sort by

recency

|

39 Discussions

|

  • + 0 comments

    Here is - HackerRank The Maximum Subarrray problem solution in Python, Java, C++, C and javascript

  • + 0 comments
    def maxSubarray(arr):
        max_ar, max_se = arr[0], 0
        curr_ar = 0
        for val in arr:
            # calculate maximum subarray
            curr_ar = max(val, curr_ar + val)
            max_ar = max(max_ar, curr_ar)
            # calculate maximum subsequence
            if val > 0:
                max_se += val
        # if all val in arr are negative
        if max_se == 0:
            max_se = max(arr)
        
        return max_ar, max_se
    
  • + 0 comments

    Kadane's max subArray sum

    function maxSubArr(nums) {    
        let current_max = nums[0], max_so_far = nums[0];
            for (let i = 1; i < nums.length; i++){
                current_max = Math.max(nums[i], current_max + nums[i]);
                max_so_far = Math.max(max_so_far, current_max);
            }
            return max_so_far;
    }
    
  • + 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
        })
    }
    
  • + 0 comments
    def maxSubarray(arr):
        max_val = max(arr)
        if max_val <= 0:
            return max_val, max_val
        max_sum = 0
        cur_sum = 0
        for i in range(len(arr)):
            if cur_sum + arr[i] < 0:
                cur_sum = 0
                continue
            cur_sum += arr[i]
            max_sum = max(max_sum, cur_sum)
        return max_sum, sum([i for i in arr if i > 0])