Experiment 1.2
Experiment 1.2
CODE:
public class Solution {
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int n3 = scanner.nextInt();
scanner.close();
}
while (true) {
if (sum1 == sum2 && sum2 == sum3) {
return sum1;
}
if (res == sum1) {
sum1 -= h1[inx1];
inx1++;
} else if (res == sum2) {
sum2 -= h2[idx2];
idx2++;
} else if (res == sum3) {
sum3 -= h3[idx3];
idx3++;
}
}
}
}
OUTPUT:
QUES 2) GAME OF STACKS:
Alexa has two stacks of non-negative integers, stack a[n] and stack b[m] where index 0 denotes
the top of the stack. Alexa challenges Nick to play the following game:
• In each move, Nick can remove one integer from the top of either stack a or stack b.
• Nick keeps a running sum of the integers he removes from the two stacks.
• Nick is disqualified from the game if, at any point, his running sum becomes greater than some
integer maxSum given at the beginning of the game.
• Nick’s final score is the total number of integers he has removed from the two stacks.
Given a, b, maxSum and for g games, find the maximum possible score Nick can achieve.
CODE:
import java.util.Scanner;
int finalScore = 0;
int sum = 0;
int i = 0;
int j = 0;
// Add elements from the first stack to the sum until maxSum is exceeded
while (i < n && sum + a[i] <= maxSum) {
sum += a[i];
i++;
}
finalScore = i; // Count of elements from the first stack
// Add elements from the second stack while removing elements from the first stack
while (j < m && i >= 0) {
sum += b[j];
j++;
// Remove elements from the first stack as long as the sum exceeds maxSum
while (i > 0 && sum > maxSum) {
i--;
sum -= a[i];
}
return finalScore;
}
}
OUTPUT:
COMPLEXITY:
The time complexity for the QUEUE is O(N2).
The time complexity for the STACK is O(1), except for the search operation which has a time
complexity of O(n).