-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDP-Loot Houses-CP Course Coding Ninjas
71 lines (63 loc) · 1.79 KB
/
DP-Loot Houses-CP Course Coding Ninjas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
Loot Houses
A thief wants to loot houses. He knows the amount of money in each house. He cannot loot two consecutive houses. Find the maximum amount of money he can loot.
Input Format :
The first line of input contains a single integer N denoting the total number of houses.
The second line of input contains N single space-separated integers, denoting the amount of money in every i-th house.
Output Format :
The only line of output will print the maximum amount of loot that is possible.
Input Constraints
0 <= N <= 10^5
0 <= A[i] <= 10^4
Where N is the total number of houses.
A[i] represents the money present in the i-th house.
Time limit: 1sec
Sample Input 1:
6
5 5 10 100 10 5
Sample Output 1 :
110
Sample Input 2:
4
10 2 3 11
Sample Output 2 :
21
Explanation to Sample Input 2:
Since the thief cant loot two consecutive houses, the ways in which he may loot are:
1. [10, 3]: a total loot of 13
2. [10, 11]: a total loot of 21
3. [2, 11]: a total loot of 13
4. [10]: a total loot of 10
5. [2]: a total loot of 2
6. [3]: a total loot of 3
7. [11]: a total loot of 11
We can't neglect the option to loot just either of the houses if it yields the maximum loot.
From all the possible seven ways, the second option yields the maximum loot amount and hence the answer.
#include<bits/stdc++.h>
using namespace std;
int main(){
// write your code here
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
if(n==0)
{
cout<<"0"<<endl;
return 0;
}
if(n==1){
cout<<arr[0]<<endl;
return 0;
}
int temp[n];
temp[n-1]=arr[n-1];
temp[n-2]=arr[n-2];
for(int i=n-3;i>=0;i--){
temp[i]=arr[i]+temp[i+2];
temp[i+1]=max(temp[i+1],temp[i+2]);
}
sort(temp,temp+n);
cout<<temp[n-1]<<endl;
return 0;
}