内容中心

2026年评价高的物流中转袋优质供应商推荐-盐城市亿德塑料包装有限公司

To solve this problem, we need to find the maximum sum of values from a subset of people such that no two people in the subset are adjacent. This is a classic dynamic programming problem, often referred to as the "House Robber" problem.

Approach

The key insight here is to use dynamic programming with space optimization. We can track two states for each person:

  1. Take: The maximum sum if we take the current person's value.
  2. Not Take: The maximum sum if we do not take the current person's value.

Dynamic Programming States:

  • Take[i]: Maximum sum up to the i-th person if we take their value. This means we cannot take the (i-1)-th person, so it equals Not Take[i-1] + a[i].
  • Not Take[i]: Maximum sum up to the i-th person if we do not take their value. This is the maximum of taking or not taking the (i-1)-th person, so it equals max(Take[i-1], Not Take[i-1]).

Space Optimization:

Instead of storing an array for Take and Not Take, we use two variables (take_prev and not_take_prev) to keep track of the previous state values. This reduces the space complexity to O(1).

Solution Code

n = int(input())
a = list(map(int, input().split()))

if n == 0:
    print(0)
elif n == 1:
    print(max(a[0], 0))
else:
    take_prev = a[0]
    not_take_prev = 0
    for num in a[1:]:
        current_take = not_take_prev + num
        current_not_take = max(take_prev, not_take_prev)
        take_prev, not_take_prev = current_take, current_not_take
    print(max(take_prev, not_take_prev))

Explanation

  1. Initialization:

    • For the first person, take_prev is their value (since taking them is an option), and not_take_prev is 0 (since not taking them gives a sum of 0).
  2. Iterate Over Remaining People:

    • For each subsequent person, compute current_take (sum if we take this person) and current_not_take (sum if we don't take this person).
    • Update take_prev and not_take_prev to the current values for the next iteration.
  3. Result:

    • The maximum sum is the maximum of take_prev (sum if we take the last person) and not_take_prev (sum if we don't take the last person). This handles all cases, including the empty subset (sum of 0).

This approach runs in O(n) time complexity (since we iterate over all people once) and O(1) space complexity (using only two variables for state tracking). It efficiently handles all edge cases, including negative values and empty subsets.

盐城市亿德塑料包装有限公司

盐城市亿德塑料包装有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?