📜  门| GATE CS 2021 |设置 2 |问题 1(1)

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

GATE CS 2021 | Setting 2 | Question 1

Introduction

This is a programming question from GATE CS 2021, under Setting 2, Question 1. The question tests the candidate's ability to write efficient code using dynamic programming.

Problem Statement

The problem involves finding the maximum sum of a subarray in an array of integers. The subarray should contain at least one element. The program should take an input array and return the maximum sum.

Approach

The problem can be solved efficiently using dynamic programming. We can create an array dp of the same size as the input array, where dp[i] represents the maximum sum of a subarray that ends at index i. We can calculate dp[i] as follows:

dp[i] = max(dp[i-1] + arr[i], arr[i])

In other words, we calculate the maximum sum ending at index i by either extending the maximum sum ending at index i-1 by adding the i-th element, or just taking the i-th element as the new subarray.

We can then find the maximum sum of a subarray by looping through the dp array and keeping track of the maximum value seen so far.

Code
def max_subarray_sum(arr):
    n = len(arr)
    dp = [0]*n
    dp[0] = arr[0]
    max_sum = dp[0]
    for i in range(1, n):
        dp[i] = max(dp[i-1]+arr[i], arr[i])
        max_sum = max(max_sum, dp[i])
    return max_sum
Complexity Analysis

The time complexity of the above algorithm is O(n), where n is the size of the input array. This is because we loop through the input array only once. The space complexity is also O(n), as we need to create an additional array of size n to store the dp array.