Press "Enter" to skip to content

Posts tagged as “house robber”

花花酱 LeetCode 740. Delete and Earn

Problem:

Given an array nums of integers, you can perform operations on the array.

In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete everyelement equal to nums[i] - 1 or nums[i] + 1.

You start with 0 points. Return the maximum number of points you can earn by applying such operations.

Example 1:

Example 2:

Note:

  • The length of nums is at most 20000.
  • Each element nums[i] is an integer in the range [1, 10000].


Idea:

Reduce the problem to House Robber Problem

Key observations: If we take nums[i]

  1. We can safely take all of its copies.
  2. We can’t take any of copies of nums[i – 1] and nums[i + 1]

This problem is reduced to 198 House Robber.

Houses[i] has all the copies of num whose value is i.

[3 4 2] -> [0 2 3 4], rob([0 2 3 4]) = 6            

[2, 2, 3, 3, 3, 4] -> [0 2*2 3*3 4], rob([0 2*2 3*3 4]) = 9

Time complexity: O(n+r) reduction + O(r) solving rob = O(n + r)

Space complexity: O(r)

r = max(nums) – min(nums) + 1

Time complexity: O(n + r)

Space complexity: O(r)

Solution:

Related Problem: