Problem Statment
Given an integer array A of N elements. You need to find the maximum sum possible of its subarray.
Example 1:
Input
3
7
1 2 3 4 -10 9 4
5
1 2 3 4 5
7
5 4 -10 -5 1 5 6
Output:
13
15
12
Given an integer array A of N elements. You need to find the maximum sum possible of its subarray.
Brute Force
One way to solve this problem is to get all the subarrays of the array and sum them individually and print the highest sum amount.
Let's look at an Optimised approach
The idea is to calculate,for each array position , the maximum sum of subarray at that position.
This method solves the problem in O(n)
test=int(input())
for i in range(test):
size=int(input())
arr=list(map(int,input().split()))
best=0
sum=0
for j in range(size):
sum=max(arr[j],arr[j]+sum)
best=max(sum,best)
print(best)