House Robber
Problem statement
nums[i] is the amount available at position i along a linear street. Choose positions to maximize the total amount, subject to selecting no two adjacent indices.
Return the maximum total as an integer. You may select no positions, giving 0. The first and last positions are adjacent only when they are consecutive indices; the street is not circular. Return the value only, not a list of selected indices. Do not modify nums.
Function
rob(nums: int[]) → intExamples
Example 1
nums = [1,2,3,1]return = 4Choose the first and third entries: 1 + 3 = 4.
Example 2
nums = [2,7,9,3,1]return = 12Choose positions 0, 2 and 4: 2 + 9 + 1 = 12.
Example 3
nums = [2,1,1,2]return = 4Choosing the first and last entries gives 4; picking only one index parity would miss this combination.
Constraints
1 <= nums.length <= 100.0 <= nums[i] <= 400.- At most 50 positions can be selected, so the result is at most
20000and fits a signed 32-bit integer.