0% found this document useful (0 votes)
10 views

DSA 3rd Sem Assignment

Uploaded by

Impana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

DSA 3rd Sem Assignment

Uploaded by

Impana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

#include <stdio.

h>
#include <limits.h>
int maximize Top Element(int stack[], int N, int K)
{
if(K==0)
{
return stack[0];
}
if (K == 1 && N == 1)
{
return -1;
}
if (K >= N)
{
int max Element = INT_MIN;
for (int i = 0; i < N; i++)
{
if (stack[i] > max Element)
{
Max Element = stack[i];
}
}
return max Element;
}
int max Element = INT_MIN;
for (int i = 0; i < K - 1; i++)
{
if (stack[i] > max Element)
{
Max Element = stack[i];
}
}
if (K < N)
{
if (stack[K] > max Element)
{
Max Element = stack[K];
}
}
return max Element;
}
int main()
{
IntN,K;
printf("En
ter the
number of
elements
in the
stack (N):
");
scanf("%
d", &N);
int stack[N];
printf("Enter the elements of the stack\n: ");
for (int i = 0; i < N; i++)
{
scanf("%d", &stack[i]);
}
printf("Enter the number of operations (K): ");
scanf("%d", &K);
int result = maximize Top Element(stack, N, K);
if (result == -1)
{
printf("-1\n");
}
else
{
printf("The maximum possible top element after %d operations is: %d\n",
K, result);
}

return 0;}
Output
Enter the number of elements in the stack (N): 5
Enter the elements of the stack: 2 6 8 9 4
Enter the number of operations (K): 2
The maximum possible top element after 2 operations is: 8

Process returned 0 (0x0) execution time : 10.652

Algorithm:
1. Start.
2. Input the number of elements (N).
3. Input the stack elements into an array stack[].
4. Input the number of operations (K).
5. Edge Case 1: If K == 0, return the top element of the stack (stack[0]).
6. Edge Case 2: If K == 1 and N == 1, return -1 since the stack will be empty
after one pop.
7. General Case for K >= N:Initialize maxElement to INT_MIN.
Return maxElement.
8. Case for K < N:Initialize maxElement to INT_MIN.
If K < N, check the K-th element (stack[K]), and update maxElement if stack[K]
is larger than the current maxElement.
Return maxElement
9.End.
Tracing:
1. Start of main() function:User inputs the values of N, stack, and K.
2. Call to maximizeTopElement():The function call is:
maximizeTopElement(stack, N, K).
3. Inside maximizeTopElement():Check for K == 0:K != 0,
so we move to the next condition.
Check for K == 1 and N == 1:K != 1, so we skip this condition as well.
Check for K >= N:K = 3, which is less than N = 5, so we skip this condition.
4. General Case (K < N):
We proceed to the main logic where we pop the first K-1 elements and find the
maximum, then compare it with the K-th element.

You might also like