📜  门| GATE-CS-2003 |第 81 题(1)

📅  最后修改于: 2023-12-03 15:28:41.687000             🧑  作者: Mango

GATE-CS-2003 Question 81

This programming question is taken from the GATE Computer Science 2003 Examination. It tests your knowledge of data structures and algorithms, and your ability to write efficient and correct code.

Problem Statement

You are given an array of integers. Write a program to find the largest sum among consecutive sub-arrays. For example, given the array [−2, 1, −3, 4, −1, 2, 1, −5, 4], the largest sum is 6 which is the sum of the consecutive sub-array [4, −1, 2, 1].

Solution

The problem can be solved using the Kadane's algorithm which is an optimized dynamic programming approach. The algorithm works by iterating over the array, and at each position keeping track of two variables: maxSoFar and maxEndingHere. maxSoFar is the maximum sum of a sub-array seen so far, and maxEndingHere is the maximum sum of a sub-array ending at the current position.

The algorithm works as follows:

  1. Initialize maxSoFar and maxEndingHere to the value of the first element of the array.
  2. Iterate over the array from the second element to the end:
    • Update maxEndingHere as the maximum of the current value and the sum of the current value and maxEndingHere.
    • Update maxSoFar as the maximum of maxSoFar and maxEndingHere.
  3. Return maxSoFar.

The time complexity of the algorithm is O(n) where n is the length of the input array, and the space complexity is O(1). The algorithm is efficient and can handle large input arrays with ease.

Code snippet
def max_subarray_sum(arr):
    """
    Returns the maximum sum among all consecutive sub-arrays of the given array.
    """
    maxSoFar = maxEndingHere = arr[0]
    for i in range(1, len(arr)):
        maxEndingHere = max(arr[i], maxEndingHere + arr[i])
        maxSoFar = max(maxSoFar, maxEndingHere)
    return maxSoFar
Conclusion

In this article, we discussed how to find the largest sum among consecutive sub-arrays of an input array. We used the Kadane's algorithm which is an optimized dynamic programming approach, and provided a Python implementation of the algorithm. We also analyzed the time and space complexity of the algorithm, and concluded that it is an efficient and scalable algorithm that can handle large input arrays with ease.