Array Consecutive Sum

Array Consecutive Sum

·

1 min read

Problem Statement : Given an array of integers, find the maximum possible sum you can get from one of its contiguous subarrays. The subarray from which this sum comes must contain at least 1 element.

int solution(int[] inputArray) {

    int maxSum = inputArray[0];    
    int currSum = inputArray[0];    
    for(int i=1; i<inputArray.length; i++) {
        // calculate current sum at each step
        currSum  = currSum + inputArray[i];
        // restart from the current element subarray if the curr sum is less than value of curr elment
        if(currSum < inputArray[i]) {
            currSum = inputArray[i];
        }
        // keep updating the maxSum at every iteration
        if(currSum > maxSum )
            maxSum = currSum;        
    }    
    return maxSum;
}

Time Complexity - O(n) - where n is the number of array elements.