📌  相关文章
📜  国际空间研究组织 | ISRO CS 2009 |问题 8(1)

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

ISRO CS 2009 - Question 8

This question is from the ISRO (Indian Space Research Organisation) CS 2009 exam. It is a problem-solving question that tests a programmer's knowledge of algorithms and data structures.

Problem Statement

Given an array of integers, find the maximum sum subarray.

For example, consider the following array: [1, -2, 3, 10, -4, 7, 2, -5].

The maximum sum subarray is [3, 10, -4, 7, 2], with a sum of 18.

Your solution should return the maximum sum and the subarray itself.

Approach

A brute-force approach would be to consider all possible subarrays and find the maximum sum. This would have a time complexity of O(n^3).

A more efficient approach is to use dynamic programming, which has a time complexity of O(n). We'll define:

  • max_so_far: the maximum sum of a subarray that ends at the current index
  • max_ending_here: the maximum sum of a subarray that ends at the current index or before

We iterate through the array, updating max_ending_here for each index. If max_ending_here becomes negative, we reset it to 0, since any subarray that includes a negative sum will not be the maximum sum. We then update max_so_far with the new max_ending_here if it is larger.

At the end of the iteration, max_so_far will hold the maximum sum and we can generate the corresponding subarray using the indices where max_ending_here was updated.

Solution

Here's the Python code that implements the approach:

def max_subarray(arr):
    max_so_far = arr[0]
    max_ending_here = 0
    start_index = 0
    end_index = 0
    
    for current_index in range(len(arr)):
        max_ending_here += arr[current_index]
        
        if max_so_far < max_ending_here:
            max_so_far = max_ending_here
            end_index = current_index
            
        if max_ending_here < 0:
            max_ending_here = 0
            start_index = current_index + 1
            
    return max_so_far, arr[start_index:end_index+1]

To test the function, we can call it with the example array:

arr = [1, -2, 3, 10, -4, 7, 2, -5]
print(max_subarray(arr))  # Output: (18, [3, 10, -4, 7, 2])

The output will show the maximum sum and the subarray itself.

Conclusion

This problem is a common interview question for programmers. It tests the ability to solve problems using efficient algorithms and data structures. The dynamic programming approach is a powerful tool for dealing with maximum sum subarray problems, and it has a time complexity of O(n).