-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ9_GuessTheNumberIsHeigherOrLower.cpp
More file actions
87 lines (64 loc) · 2.11 KB
/
Q9_GuessTheNumberIsHeigherOrLower.cpp
File metadata and controls
87 lines (64 loc) · 2.11 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<iostream>
#include<vector>
using namespace std;
int byRecursion(int start , int end){
//base case
if(start >= end){
return 0;
}
int ans = INT8_MAX;
for(int i = start; i <=end;i++){
ans = min(ans, i + max(byRecursion(start, i-1) , byRecursion(i+1, end))); //is line ka i + max bhool jayeaga i for current iteration
}
return ans;
}
int byTopBottom(int start , int end , vector<vector<int> >&dp){
// base case
if(start >= end){
return 0;
}
int ans = INT8_MAX;
//step3: check if the answer is already exist
if(dp[start][end] != -1){
return dp[start][end];
}
for(int i= start ; i<= end; i++){
ans = min(ans , i + max(byTopBottom(start , i-1 ,dp) , byTopBottom(i+1 , end , dp) ));
}
//step2: storing the ans to the dp
dp[start][end] = ans; //dp meein jo badal rhe hain woh rakho
return dp[start][end];
}
int byTabulation(int n ){
///step1 : creating the DP array
vector<vector<int> > dp(n+2 , vector<int>(n+2 , 0));
// flow of the code
for(int start = n ; start >= 1 ; start--){
for(int end = 1 ; end <= n ; end++){
//logic
if(start >=end){
continue;
}
//initializing the ans ;
int ans = INT8_MAX;
for(int i= start ; i<= end; i++){
ans = min(ans , i + max(dp[start][i-1] , dp[i+1][end] ));
}
//step2: storing the ans to the dp
dp[start][end] = ans; //dp meein jo badal rhe hain woh rakho
}
}
return dp[1][n];
}
int main(){
int n = 10;
int ans = byRecursion(1, n);
//by top down optimisation
//step 1 : creating the 2d array
vector<vector<int> > dp(n+2, vector<int>(n+2 , -1)); //take care here create +2 range
int ans2 =byTopBottom(1, n , dp);
//by tabulation
int ansByTabulation = byTabulation(n);
cout<<"answer is : "<<ansByTabulation<<endl;
return 0;
}