Skip to content

Commit 46f0d68

Browse files
committed
Added new algorithms
1 parent 052ae3a commit 46f0d68

File tree

3 files changed

+116
-0
lines changed

3 files changed

+116
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
2+
#include <iostream>
3+
4+
#define MAX_EGGS 100
5+
#define MAX_FLOORS 100
6+
#define INF 1000000000
7+
8+
using namespace std;
9+
10+
int memo[MAX_EGGS][MAX_FLOORS];
11+
12+
/*
13+
* Returns the minimum number of attempts
14+
* needed in the worst case for n eggs
15+
* and k floors.
16+
* Time complexity: O(n*k^2)
17+
*/
18+
int eggDrop(int n, int k) {
19+
20+
if(k == 0) return 0;
21+
if(k == 1) return 1;
22+
if(n == 1) return k;
23+
24+
25+
if(memo[n][k] > -1) return memo[n][k];
26+
27+
int ans = INF;
28+
for(int h = 1; h <= k; ++h) {
29+
30+
ans = min(ans, max(
31+
eggDrop(n-1, h-1),
32+
eggDrop(n, k-h)
33+
));
34+
}
35+
36+
return memo[n][k] = ans + 1;
37+
}
38+
39+
int main() {
40+
41+
memset(memo, -1, sizeof memo);
42+
43+
cout << eggDrop(2, 100) << '\n';
44+
cout << eggDrop(10, 5) << '\n';
45+
cout << eggDrop(10, 100) << '\n';
46+
return 0;
47+
}
48+

DP/Tiling Problem/tiling.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include<iostream>
2+
#include<vector>
3+
using namespace std;
4+
5+
long long tiling(int n)
6+
{
7+
vector<long long int> tile(n+1);
8+
9+
tile[0]=1;
10+
tile[1]=1;
11+
tile[2]=2;
12+
for(int i=3;i<=n;i++)
13+
{
14+
tile[i]=tile[i-1]+tile[i-2];
15+
}
16+
return tile[n];
17+
}
18+
19+
int main()
20+
{ int n;
21+
cout<<"enter the value of n\n";
22+
cin>>n;
23+
cout<<"total ways to arrange the tiles is "<<tiling(n);
24+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
int binarySearch(int arr[], int, int, int);
6+
7+
int exponentialSearch(int arr[], int n, int x)
8+
{
9+
if (arr[0] == x)
10+
return 0;
11+
12+
int i = 1;
13+
while (i < n && arr[i] <= x)
14+
i = i*2;
15+
16+
return binarySearch(arr, i/2, min(i, n), x);
17+
}
18+
19+
int binarySearch(int arr[], int l, int r, int x)
20+
{
21+
if (r >= l)
22+
{
23+
int mid = l + (r - l)/2;
24+
if (arr[mid] == x)
25+
return mid;
26+
if (arr[mid] > x)
27+
return binarySearch(arr, l, mid-1, x);
28+
29+
return binarySearch(arr, mid+1, r, x);
30+
}
31+
return -1;
32+
}
33+
34+
int main(void)
35+
{
36+
int arr[] = {2, 3, 4, 10, 40};
37+
int n = sizeof(arr)/ sizeof(arr[0]);
38+
int x = 10;
39+
int result = exponentialSearch(arr, n, x);
40+
(result == -1)? printf("Element is not present in array")
41+
: printf("Element is present at index %d",
42+
result);
43+
return 0;
44+
}

0 commit comments

Comments
 (0)