Skip to content

Commit 9647da6

Browse files
committed
new question added
1 parent d11036b commit 9647da6

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@ For eg storing the minimum so far in another stack so that each time when a numb
6060
- Some algos may require implementing a stack using a different data structure. For eg using Double linked list over single linked list or using single linked list over arrays and so on. (question 7)
6161

6262
### Heaps (methods that can be applied):
63-
-
63+
- A large heap can be delcared and only a small portion of it can always be included in the heap operations.
64+
- Whenever a heap is built, swapping etc. will be there if elements do not follow the heap property (max or min)
65+
6466

6567
# Topic0: Programming Questions
6668

@@ -179,6 +181,7 @@ For eg storing the minimum so far in another stack so that each time when a numb
179181
- [Given an array, create a max heap](/heaps/question1.c)
180182
- [Given a max heap, apply different heap operations (find max, delete max,increase key, insert key, decrease key.)](/heaps/question2.c)
181183
- [Write a program for heap sort](/heaps/question3.c)
184+
- [Find a max element in a min-heap](/heaps/question4.c)
182185

183186
## Some important concepts to solve algos better
184187

@@ -201,7 +204,7 @@ For eg storing the minimum so far in another stack so that each time when a numb
201204
- From an array if a heap is to be constructed, follow:
202205

203206
```C
204-
LEFT(i) = 2i + 1;
207+
LEFT(i) = 2i + 1;
205208
RIGHT(i) = 2i + 2;
206209
PARENT(i) = (i-1) / 2; (valid for array with index 0)
207210
//Go level by level from left to right and write elements from the array or to the array basically.

heaps/question4.c

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Find a max element in a min-heap
3+
4+
TIme complexity: O(n)
5+
6+
We know that the max element in a min-heap is going to be in the leaves only.
7+
There are atleast n/2 leaves and if we scan through these elements (which is the only way), it will take
8+
O(n) time
9+
*/
10+
11+
#include <stdio.h>
12+
#include <stdlib.h>
13+
#include <math.h>
14+
15+
int findMax(int arr[], int size){
16+
int index = floor(size/2) + 1;
17+
int max = arr[index];
18+
for(int i=index+1;i<size;i++){
19+
if(arr[i]>max){
20+
max = arr[i];
21+
}
22+
}
23+
24+
return max;
25+
26+
}
27+
28+
int main(){
29+
int minHeap[] = {1,3,5,7,9,8,10,11,12};
30+
int size = sizeof(minHeap)/sizeof(minHeap[0]);
31+
int max = findMax(minHeap, size);
32+
33+
printf("max element in the min heap is %d\n", max);
34+
35+
return 0;
36+
}

0 commit comments

Comments
 (0)