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;