Answers for "return maximum subarray"

C++
2

kadane algorithm

public int kadane(int[] arr){
	int max_so_far = 0, curr_max = Integer.MIN_VALUE;
    for(int i: arr){
    	max_so_far += i;
        if(max_so_far<0) max_so_far = 0;
        if(max_so_far>curr_max) curr_max = max_so_far;
    }
    return curr_max;
}
Posted by: Guest on June-20-2020
1

max subsequence sum in array

def max_subarray(numbers):
    """Find the largest sum of any contiguous subarray."""
    best_sum = 0  # or: float('-inf')
    current_sum = 0
    for x in numbers:
        current_sum = max(0, current_sum + x)
        best_sum = max(best_sum, current_sum)
    return best_sum
Posted by: Guest on September-14-2020
0

kadane algorithm with negative numbers included as sum

//Usually Kadene's algorithm is not considered for negative numbers.   
  int ms,cs;
	    ms=cs=a[0]; 
	    for(int i=1;i<n;i++)
	    {
	        cs=max(a[i],cs+a[i]);
	       ms=max(cs,ms);
	}
return ms;
Posted by: Guest on October-23-2020

Browse Popular Code Answers by Language