亚马逊面试题:打家劫舍问题(非相邻最大和 | 动态规划)

70次阅读
没有评论

You are given an array of integers representing the amount of money stored in each house.
The houses are arranged in a line, and you cannot rob two adjacent houses.

Return the maximum amount of money you can rob without ever robbing two adjacent houses.

Example

Input:  [5, 1, 2, 6, 20, 2]
Output: 27          # 5 + 6 + 20 = 31? → Actually the optimal is 5 + 2 + 20 = 27

(Explanation: choose non-adjacent houses so the sum is maximized.)


使用 动态规划
dp[i] = max(dp[i-1], dp[i-2] + nums[i]),表示抢或不抢当前房子,两者取较大值。
最终答案为 dp[n-1]

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0