0% found this document useful (0 votes)
0 views3 pages

Assignment

The document contains solutions to three programming problems related to algorithms. The first problem demonstrates both a brute-force and an optimized approach using a stack to find the next greater element in an array. The second problem calculates the amount of trapped rainwater, while the third identifies the majority element in an array using a counting method.

Uploaded by

rajasharma8865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views3 pages

Assignment

The document contains solutions to three programming problems related to algorithms. The first problem demonstrates both a brute-force and an optimized approach using a stack to find the next greater element in an array. The second problem calculates the amount of trapped rainwater, while the third identifies the majority element in an array using a counting method.

Uploaded by

rajasharma8865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

My name is Raja Sharma, Btech CSE Final year student and this is my IA 1 of AAPS summer .

21SCSE1011085

Ans1

Brute-force Approach:

void printNGE(int arr[], int n) {

for (int i = 0; i < n; i++) {

int next = -1;

for (int j = i + 1; j < n; j++) {

if (arr[j] > arr[i]) {

next = arr[j];

break;

cout << arr[i] << " -> " << next << endl;

Optimized Approach (Using Stack):

void printNGE(int arr[], int n) {

stack<int> s;

vector<int> res(n, -1);

for (int i = n - 1; i >= 0; i--) {

while (!s.empty() && s.top() <= arr[i])

s.pop();
if (!s.empty()) res[i] = s.top();

s.push(arr[i]);

for (int i = 0; i < n; i++)

cout << arr[i] << " -> " << res[i] << endl;

Ans 2

int trap(int height[], int n) {

int left[n], right[n];

left[0] = height[0];

for (int i = 1; i < n; i++)

left[i] = max(left[i-1], height[i]);

right[n-1] = height[n-1];

for (int i = n-2; i >= 0; i--)

right[i] = max(right[i+1], height[i]);

int water = 0;

for (int i = 0; i < n; i++)

water += min(left[i], right[i]) - height[i];

return water;

}
Ans 3

int findMajorityElement(int arr[], int n) {

int count = 0, candidate = -1;

for (int i = 0; i < n; i++) {

if (count == 0) {

candidate = arr[i];

count = 1;

} else {

count += (arr[i] == candidate) ? 1 : -1;

count = 0;

for (int i = 0; i < n; i++)

if (arr[i] == candidate) count++;

return (count > n/2) ? candidate : -1;

You might also like