Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trapping rainwater #3481

Merged
merged 2 commits into from
Oct 30, 2022
Merged
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
43 changes: 43 additions & 0 deletions others/BoyerMoore/BoyerMooreVoting.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <iostream>
using namespace std;
// Function to find majority element
int findMajority(int arr[], int n)
{
int i, candidate = -1, votes = 0;
// Finding majority candidate
for (i = 0; i < n; i++)
{
if (votes == 0)
{
candidate = arr[i];
votes = 1;
}
else
{
if (arr[i] == candidate)
votes++;
else
votes--;
}
}
int count = 0;
// Checking if majority candidate occurs more than n/2
// times
for (i = 0; i < n; i++)
{
if (arr[i] == candidate)
count++;
}

if (count > n / 2)
return candidate;
return -1;
}
int main()
{
int arr[] = {1, 1, 1, 1, 2, 3, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int majority = findMajority(arr, n);
cout << " The majority element is : " << majority;
return 0;
}
41 changes: 41 additions & 0 deletions others/TrappingRainwater/TrappingRainwater.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <bits/stdc++.h>
using namespace std;

int findWater(int arr[], int n)
{
int left[n];
int right[n];

// Initialize result
int water = 0;

// Fill left array
left[0] = arr[0];
for (int i = 1; i < n; i++)
left[i] = max(left[i - 1], arr[i]);

// Fill right array
right[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--)
right[i] = max(right[i + 1], arr[i]);

for (int i = 1; i < n - 1; i++)
{
int var = min(left[i - 1], right[i + 1]);
if (var > arr[i])
{
water += var - arr[i];
}
}

return water;
}

// Driver program
int main()
{
int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << findWater(arr, n);
return 0;
}