FastPrepHouse Robber

House Robber

Headlands Technologies logoHeadlands Technologies● MediumFULLTIMEONSITE INTERVIEW
Learn

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[]) → int

Examples

Example 1

nums = [1,2,3,1]return = 4

Choose the first and third entries: 1 + 3 = 4.

Example 2

nums = [2,7,9,3,1]return = 12

Choose positions 0, 2 and 4: 2 + 9 + 1 = 12.

Example 3

nums = [2,1,1,2]return = 4

Choosing 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 20000 and fits a signed 32-bit integer.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public int rob(int[] nums) {
    // write your code here
}
nums[1,2,3,1]
expected4
Checking account…