Skip to content

Commit 1112d41

Browse files
Merge pull request #5 from de1401/main
added loot_houses in O(1) space
2 parents def5707 + 279a4e2 commit 1112d41

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

dynamic_programming_1/loot_houses.cpp

+11-13
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,17 @@ Sample Output 1 :
1616
*/
1717
#include<bits/stdc++.h>
1818
using namespace std;
19-
int getMaxMoney(int arr[], int n){
19+
int maxMoneyLooted(int *arr, int n)
20+
{
21+
//Write your code here
22+
if (n == 1) return arr[0];
2023

21-
/*Write your code here.
22-
*Don’t write main().
23-
*Don’t take input, it is passed as function argument.
24-
*Don’t print output.
25-
*Taking input and printing output is handled automatically.
26-
*/
27-
int dp[n];
28-
dp[0] = arr[0];
29-
dp[1] = arr[1];
30-
for(int i = 2; i < n; i++){
31-
dp[i] = arr[i] + max(dp[i - 2], dp[i - 3]);
24+
int prev = arr[0];
25+
int curr = max(arr[0], arr[1]);
26+
for (int i = 2; i < n; i++) {
27+
int temp = curr;
28+
curr = max(curr, prev + arr[i]);
29+
prev = temp;
3230
}
33-
return max(dp[n - 1], dp[n - 2]);
31+
return max(prev, curr);
3432
}

0 commit comments

Comments
 (0)