πDay 18. Stickler Thief π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Stickler the thief wants to loot money from houses arranged in a line. However, he cannot loot two consecutive houses to avoid being caught. His goal is to maximize the total amount looted.
Given an array arr[], where arr[i]
represents the amount of money in the i
-th house, determine the maximum amount he can loot.
π Example Walkthrough:
Example 1:
Input:
arr[] = [6, 5, 5, 7, 4]
Output:
15
Explanation:
Maximum loot can be obtained by robbing the 1st, 3rd, and 5th houses: 6 + 5 + 4 = 15
Example 2:
Input:
arr[] = [1, 5, 3]
Output:
5
Explanation:
Best choice is to loot only the 2nd house, obtaining 5.
Example 3:
Input:
arr[] = [4, 4, 4, 4]
Output:
8
Explanation:
Stickler can loot either the 1st & 3rd houses or 2nd & 4th houses for a total of 4 + 4 = 8.
Constraints:
$1 \leq \text{arr.size()} \leq 10^5$
$1 \leq \text{arr}[i] \leq 10^4$
π― My Approach:
Optimized Dynamic Programming
Algorithm Steps:
Maintain two variables:
prev2
β Stores the loot obtained up to the house before the previous one.prev1
β Stores the loot obtained up to the previous house.
Iterate through the array:
For each house
arr[i]
, decide whether to loot it or skip it.If looted, the total becomes
prev2 + arr[i]
.If skipped, the total remains
prev1
.Update
prev2
andprev1
accordingly.
Return
prev1
as the final answer.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), since we iterate over the array once.
Expected Auxiliary Space Complexity: O(1), as we use only a few variables.
π Solution Code
Code (C++)
class Solution {
public:
int findMaxSum(vector<int>& arr) {
int prev2 = 0, prev1 = 0;
for (int num : arr) {
int temp = max(prev1, prev2 + num);
prev2 = prev1;
prev1 = temp;
}
return prev1;
}
};
Code (Java)
class Solution {
public int findMaxSum(int[] arr) {
int prev2 = 0, prev1 = 0;
for (int num : arr) {
int temp = Math.max(prev1, prev2 + num);
prev2 = prev1;
prev1 = temp;
}
return prev1;
}
}
Code (Python)
class Solution:
def findMaxSum(self, arr):
prev2 = prev1 = 0
for num in arr:
prev2, prev1 = prev1, max(prev1, prev2 + num)
return prev1
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated