Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Problems and General Algos/Moore's_Voting_Algo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <bits/stdc++.h>
using namespace std;

//Majority element is the element which appears more than n/2 times in an array,
//where n is the size of the array.

//Function to calculate the majority element
int fun(vector<int> v){
//Variable 'ele' to store the majority element
int ele=v[0];
int k=1;
for(int i=1;i<v.size();i++){
if(v[i]==ele)
k++;
else
k--;
if(k==0){
ele=v[i];
k=1;
}
}
return ele;
}

int main() {
vector<int> v({3,2,4,3,3,3});
int ans=fun(v);
int k=0;
for(int i=0;i<v.size();i++){
if(v[i]==ans)
k++;
}
if(k>v.size()/2)
cout<<"Majority element is "<<ans;
else
cout<<"No majority element";
return 0;
}
31 changes: 31 additions & 0 deletions Problems and General Algos/Trapping_rainwater.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <bits/stdc++.h>
using namespace std;

int fun(vector<int>& height){
int n=height.size();
if(n==0) return 0;
stack<int> s;
int top,distance,length;
int curr=0;
int ans=0;
while(curr<n){
while(!s.empty() && height[curr]>height[s.top()]){
top=s.top();
s.pop();
if(s.empty())
break;
distance=curr-s.top()-1;
length=((height[curr]<height[s.top()])?height[curr]:height[s.top()])-height[top];
ans+=distance*length;
}
s.push(curr);
curr++;
}
return ans;
}

int main() {
vector<int> v({0,1,0,2,1,0,1,3,2,1,2,1});
cout<<"The amount of trapped rainwater is "<<fun(v);
return 0;
}