📅  最后修改于: 2023-12-03 14:50:46.673000             🧑  作者: Mango
The International Space Research Organization (ISRO) is an Indian space agency that is responsible for the research and development of space technology. In the ISRO CS 2013 exam, there was a question (Question 15) related to programming. The question required the programmer to write a function that finds the maximum sum of any contiguous subarray of a given array.
Given an array A of N integers, find the maximum sum of any contiguous subarray of the array.
Input
The first line of the input contains an integer T, the number of test cases. Each test case consists of two lines. The first line contains an integer N, the size of the array. The second line contains N integers, the elements of the array.
Output
For each test case, output the maximum sum of any contiguous subarray of the array.
Constraints
1 ≤ T ≤ 50
1 ≤ N ≤ 100000
-100000 ≤ A[i] ≤ 100000
Example
Input:
2
3
1 2 3
4
-1 -2 -3 -4
Output:
6
-1
The approach to solve this problem is by using Kadane's algorithm. Kadane's algorithm is a very popular algorithm to solve this type of problem. It uses dynamic programming to solve the problem in linear time.
The basic idea of Kadane's algorithm is to keep track of the maximum sum subarray ending at each index in the array. We initialize two variables max_so_far
and max_ending_here
to 0. We loop through each element in the array, updating max_ending_here
as the sum of the current element and the previous sum. If the max_ending_here
is less than 0, we reset it to 0. At each iteration, we update max_so_far
with the maximum value of max_so_far
and max_ending_here
.
Here's the Python code to solve the problem:
def max_subarray_sum(A):
max_so_far = A[0]
max_ending_here = A[0]
for i in range(1, len(A)):
max_ending_here = max(max_ending_here+A[i], A[i])
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
T = int(input())
for _ in range(T):
n = int(input())
A = list(map(int, input().split()))
print(max_subarray_sum(A))
In conclusion, Kadane's algorithm is a very popular and efficient way to solve the maximum sum subarray problem. By using dynamic programming, we can solve the problem in linear time. The solution provided here is in Python, but the same algorithm can be implemented in other programming languages as well.