📜  门| GATE CS Mock 2018 |设置 2 |问题 5(1)

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

GATE CS Mock 2018 - Set 2 - Question 5

This is a coding problem from the GATE CS Mock 2018 - Set 2 - Question 5. The problem statement is as follows:

Problem Statement

Given an array of integers, find the maximum sum of non-adjacent elements.

Input

The first line of input contains an integer T denoting the number of test cases. Each test case contains an integer n denoting the size of the array, followed by n integers.

Output

For each test case, output the maximum sum of non-adjacent elements.

Solution

To solve this problem, we can use dynamic programming. We can define an array dp such that dp[i] represents the maximum sum we can get using elements up to and including the i-th element of the input array.

The recurrence relation for dp can be defined as follows:

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

Here, arr is the input array and dp[i-1] represents the maximum sum we can get by including the (i-1)th element, while dp[i-2]+arr[i] represents the maximum sum we can get by excluding the (i-1)th element and including the i-th element.

Finally, we just need to return dp[n-1], which will give us the maximum sum we can get using all the elements of the input array.

Here's the Python implementation of the solution:

def maxSum(arr):
    n = len(arr)

    if n == 0:
        return 0

    if n == 1:
        return arr[0]

    dp = [0] * n

    dp[0] = arr[0]
    dp[1] = max(arr[0], arr[1])

    for i in range(2, n):
        dp[i] = max(dp[i-1], dp[i-2]+arr[i])

    return dp[n-1]


# Sample Input
"""
2
4
3 2 5 10
5
10 5 1 20 15
"""

# Sample Output
"""
13
35
"""
Explanation

In the first test case, the maximum sum we can get using non-adjacent elements is 13, which is obtained by including elements at indices 0 and 3.

In the second test case, the maximum sum we can get using non-adjacent elements is 35, which is obtained by including elements at indices 0, 2, and 4.