📅  最后修改于: 2023-12-03 15:23:03.603000             🧑  作者: Mango
This problem is from the Indian Space Research Organization (ISRO) Computer Science 2014 test.
Given a list of numbers, we need to find the maximum sum that can be obtained by choosing some elements from the list such that no two elements are adjacent.
Input: [4, 1, 1, 4, 2, 1]
Output: 9
Input: [5, 1, 2, 6, 20, 17]
Output: 27
To solve this problem, we can use dynamic programming. We define an array dp
of the same length as the input array, where dp[i]
represents the maximum sum that can be obtained by choosing some elements from the input array up to index i
such that element i
is included.
The recursive formula to compute this dp
array is as follows:
For i=0, dp[0]=nums[0]
For i=1, dp[1]=max(nums[0],nums[1])
For i>1, dp[i]=max(dp[i-2]+nums[i],dp[i-1])
The maximum sum we are looking for would then be the last element of the dp
array.
Here's the Python implementation of the above algorithm:
def find_max_sum(nums):
n = len(nums)
# Base Cases
if n == 0:
return 0
if n == 1:
return nums[0]
if n == 2:
return max(nums[0], nums[1])
# Initialization
dp = [0]*n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
# Compute dp array
for i in range(2, n):
dp[i] = max(dp[i-2] + nums[i], dp[i-1])
return dp[-1] # Return last element of dp array
To use the above code, simply call the find_max_sum
function with the input list as argument:
nums = [4, 1, 1, 4, 2, 1]
print(find_max_sum(nums)) # Output: 9
In this problem, we have demonstrated how to use dynamic programming to find the maximum sum of non-adjacent elements in a list. This algorithm has a time complexity of O(n) and a space complexity of O(n).