C++ 0198.cpp
class Solution {
map<int, int> cache;
int dp(vector<int>& nums, int next)
{
if (next >= nums.size())
return 0;
if (cache.count(next) > 0)
return cache[next];
int best = 0;
for (int i = next; i < nums.size(); i++)
{
auto current = nums[i] + dp(nums, i + 2);
if (best < current)
best = current;
}
cache[next] = best;
return best;
}
public:
int rob(vector<int>& nums) {
cache.clear();
return dp(nums, 0);
}
};
Difficulty
and has an acceptance rate of about 53% (7+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented class implements a dynamic-programming solution for the classic “house robber” problem. The public method rob receives a vector of integers representing the amount of money in each house and returns the maximum sum that can be obtained without robbing two adjacent houses. The core logic resides in the private recursive function dp, which explores the decision space while caching intermediate results to avoid redundant computation.
Key Components
The solution is organized around three main elements: a memoization container, a recursive helper, and the public entry point.
The memoization container is declared as a member variable:
map<int, int> cache;
It maps a starting index to the best achievable sum from that position onward.
The recursive helper dp follows a clear structure. The first guard handles the termination condition when the index exceeds the array bounds:
if (next >= nums.size())
return 0;
The second guard checks whether the result for the current index has already been computed:
if (cache.count(next) > 0)
return cache[next];
The core of the algorithm iterates over all possible choices starting from next. For each house i, it adds the house’s value to the optimal result obtained by skipping the next house (i + 2). The loop maintains the maximum of these candidates:
int best = 0;
for (int i = next; i < nums.size(); i++)
{
auto current = nums[i] + dp(nums, i + 2);
if (best < current)
best = current;
}
After the loop, the computed best value is stored in the cache and returned:
cache[next] = best;
return best;
The public method prepares the environment by clearing any previous cache entries and invoking the helper from the first house:
int rob(vector<int>& nums) {
cache.clear();
return dp(nums, 0);
}
Edge Cases Handled
The implementation explicitly addresses several boundary conditions:
When the input vector is empty, the initial call to dp receives next == 0 and the size check next >= nums.size() triggers an immediate return of 0. This correctly yields a maximum loot of zero.
When the vector contains a single element, the loop in dp runs once, adding that element’s value to the result of dp(nums, 2). The recursive call reaches the termination guard and returns 0, so the final answer equals the sole house’s amount.
When the vector contains two elements, the loop evaluates both houses individually. Each iteration adds the house’s value to the result of dp called with an index beyond the array, which again returns 0. The maximum of the two values is selected, ensuring that the algorithm respects the non-adjacent constraint.
If the recursion reaches an index that is exactly one past the last element (next == nums.size() - 1), the loop still processes the final house, and the subsequent call to dp(nums, i + 2) safely lands beyond the array, invoking the base case.
Performance Considerations
The use of a map for caching introduces logarithmic lookup and insertion costs, which is a deliberate trade-off for the flexibility of associative containers. Because each distinct starting index is evaluated at most once, the algorithm avoids the exponential blow-up typical of naïve recursive solutions.
The inner loop iterates from the current index to the end of the vector, accumulating the best achievable sum for that segment. Although this results in a quadratic number of total iterations across all distinct next values, the memoization ensures that each sub-problem is solved only once, eliminating repeated work.
Clearing the cache at the beginning of rob guarantees that multiple invocations on different input vectors do not interfere with one another, preserving correctness without incurring additional overhead during the computation itself.
Overall, the design balances simplicity with effective reuse of previously computed results, delivering a solution that scales reasonably for moderate input sizes while maintaining clear and maintainable code structure.
ELI5 - Simplified Explanation
Imagine there is a long row of little houses, and each house has some coins inside. The goal is to collect as many coins as possible, but there is a rule that you cannot take coins from two houses that are right next to each other. If you take coins from the first one, you must skip the second one and go to the third.
The code works by looking at every house one by one to decide if taking those coins leads to the biggest pile in the end. It uses a clever trick called a cache, which is just like a notebook where it writes down the answer for a house after it figures it out once. That way, if it ever needs to know the answer for that same house again, it does not have to do the hard work of counting all over again.
The function starts at the very first house and keeps jumping forward, adding up coins while always skipping the neighbor to follow the rules. It keeps track of the best total it has found so far by comparing the treasures from different paths. When it reaches the end of the street, it knows exactly which plan gives the most coins. The clear command at the start just makes sure the notebook is empty before starting a brand new game of coin collecting.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | JS | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| everthis | JS | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| everthis | JavaScript | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 152: Maximum Product Subarray
- problem 213: House Robber II
- problem 740: Delete and Earn
- problem 2320: Count Number of Ways to Place Houses
- problem 2560: House Robber IV
- problem 2611: Mice and Cheese
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality