Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. code example
Example 1: Write a program to find the sum of all sub-arrays of a given integer array.
long int SubArraySum( int arr[] , int n )
{
long int result = 0;
// computing sum of subarray using formula
for (int i=0; i<n; i++)
result += (arr[i] * (i+1) * (n-i));
// return all subarray sum
return result ;
}
Example 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;
}