DP Approach:
This problem can be solved using Dynamic Programming. Let’s define two terms:
the optimal sub-array sum up to index by keeping the value of index itself
the value of the array at index .
If we take an array index and calculate the maximum sub-array sum by keeping the value of index , then we have only two options. We can either take only the value at position , or we can add the value of position with the maximum sub-array sum up to index . So, the answer for would be the maximum of and . The solution of the entire problem would be the maximum of all the from index to . The time complexity of the DP solution would be , where is the size of the array.