📅  最后修改于: 2023-12-03 15:07:35.018000             🧑  作者: Mango
This is a coding problem from ISRO CS 2018 exam.
You are given an array of integers. Find the largest sum of contiguous subarray of the given array.
The first line of input contains an integer T, representing the number of test cases. For each test case, the first line contains an integer N, representing the size of the array. The second line contains N space-separated integers representing the array.
For each test case, print the largest sum of contiguous subarray of the given array, in a new line.
Input:
2
5
-1 2 3 -4 5
4
-1 -2 -3 -4
Output:
7
-1
One way to solve this problem is to implement Kadane's Algorithm. Kadane's Algorithm finds a subarray with the largest sum in a given array. It does so in a single pass over the array.
Let A
be the input array. Let max_so_far
and max_ending_here
be two variables that keep track of the largest sum so far and largest sum ending at the current index, respectively. Then, the algorithm can be implemented as follows:
max_so_far = max_ending_here = A[0]
for i = 1 to n-1
max_ending_here = max(A[i], max_ending_here + A[i])
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
The above algorithm has a time complexity of O(n).
Here's the Python code to solve the problem:
def kadane(arr):
n = len(arr)
max_so_far = max_ending_here = arr[0]
for i in range(1, n):
max_ending_here = max(arr[i], max_ending_here+arr[i])
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
# Main function
if __name__ == '__main__':
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().split()))
print(kadane(arr))
The kadane
function implements Kadane's Algorithm, as described above. The main function reads input from the user, calls the kadane
function for each test case, and prints the maximum sum of contiguous subarray for each test case.
In this problem, we learned about Kadane's Algorithm - a linear-time algorithm to find the largest sum of contiguous subarray of a given array. The algorithm can be useful in solving several other related problems as well.