2B)
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Program2b{
  Queue<Integer> q1 = new LinkedList<>();
  Queue<Integer> q2 = new LinkedList<>();
  public void push(int x) {
      q2.add(x);
      while (!q1.isEmpty()) {
          q2.add(q1.remove());
      Queue<Integer> temp = q1;
      q1 = q2;
      q2 = temp;
      System.out.println("Pushed: " + x);
  public int pop() {
      if (q1.isEmpty()) {
          System.out.println("Stack is empty!");
          return -1;
      return q1.remove();
  public int top() {
      if (q1.isEmpty()) {
          System.out.println("Stack is empty!");
        return -1;
    return q1.peek();
public boolean isEmpty() {
    return q1.isEmpty();
public void display() {
    if (q1.isEmpty()) {
        System.out.println("Stack is empty!");
        return;
    System.out.println("Stack contents (top to bottom): " + q1);
public static void main(String[] args) {
    Program2b stack = new Program2b();
    Scanner sc = new Scanner(System.in);
    int choice, value;
    do {
        System.out.println("\n1. Push\n2. Pop\n3. Top\n4. Display\n5. Exit");
        System.out.print("Enter your choice: ");
        choice = sc.nextInt();
        switch (choice) {
           case 1:
             System.out.print("Enter value to push: ");
             value = sc.nextInt();
             stack.push(value);
                break;
              case 2:
                int popped = stack.pop();
                if (popped != -1)
                  System.out.println("Popped: " + popped);
                break;
              case 3:
                int top = stack.top();
                if (top != -1)
                  System.out.println("Top element: " + top);
                break;
              case 4:
                stack.display();
                break;
              case 5:
                System.out.println("Exiting...");
                break;
              default:
                System.out.println("Invalid choice.");
        } while (choice != 5);
        sc.close();
6a)
import java.util.HashMap;
import java.util.Scanner;
public class Program6a {
  public static int[] twoSum(int[] nums, int target) {
      HashMap<Integer, Integer> map = new HashMap<>();
      for (int i = 0; i < nums.length; i++) {
          int complement = target - nums[i];
          if (map.containsKey(complement)) {
              return new int[] { map.get(complement), i };
          map.put(nums[i], i);
      return new int[]{}; // This was misplaced before
  public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter the number of elements in the array: ");
      int n = sc.nextInt();
      int[] nums = new int[n];
      System.out.print("Enter the array elements: ");
      for (int i = 0; i < n; i++) {
          nums[i] = sc.nextInt();
      System.out.print("Enter the target sum: ");
      int target = sc.nextInt();
      int[] result = twoSum(nums, target);
      if (result.length == 0) {
          System.out.println("No solution found.");
      } else {
          System.out.println("Indices of the two numbers: [" + result[0] + ", " + result[1] + "]");
      sc.close();
  } }
Set -13a)
import java.util.*;
public class AssignCookies {
  public static int findContentChildren(int[] greed, int[] cookies) {
      Arrays.sort(greed);
      Arrays.sort(cookies);
      int i = 0, j = 0;
      while (i < greed.length && j < cookies.length) {
          if (cookies[j] >= greed[i]) {
              i++;
          j++;
      return i;
  public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter number of children:");
      int n = sc.nextInt();
        int[] greed = new int[n];
        System.out.println("Enter greed factors:");
        for (int i = 0; i < n; i++) {
            greed[i] = sc.nextInt();
        System.out.println("Enter number of cookies:");
        int m = sc.nextInt();
        int[] cookies = new int[m];
        System.out.println("Enter cookie sizes:");
        for (int i = 0; i < m; i++) {
            cookies[i] = sc.nextInt();
        int result = findContentChildren(greed, cookies);
        System.out.println("Maximum number of children that can be satisfied: " + result);
        sc.close();
Set14
14a)
import java.util.*;
public class LemonadeStand {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Integer> payments = new ArrayList<>();
int five = 0, ten = 0;
System.out.println("Welcome to the Lemonade Stand!");
while (true) {
  System.out.print("Enter payment amount of the customer (or type 'exit' to quit): ");
  String input = sc.nextLine();
  if (input.equalsIgnoreCase("exit")) break;
  int payment = Integer.parseInt(input);
  if (payment == 5) {
     five++;
     System.out.println("Customer served. Change given: 0");
  } else if (payment == 10) {
     if (five >= 1) {
         five--;
         ten++;
         System.out.println("Customer served. Change given: 5");
     } else {
         System.out.println("Cannot give change. Transaction failed.");
         break;
  } else if (payment == 20) {
     if (ten >= 1 && five >= 1) {
         ten--;
         five--;
         System.out.println("Customer served. Change given: 15");
     } else if (five >= 3) {
                     five -= 3;
                     System.out.println("Customer served. Change given: 15");
                 } else {
                     System.out.println("Cannot give change. Transaction failed.");
                     break;
         sc.close();
    Set 17
17a)
import java.util.Scanner;
class Node {
     int data;
     Node left, right;
     Node(int item) {
         data = item;
         left = right = null;
public class CountPathsBinaryTree {
     public static int countPaths(Node root) {
         return countPathsUtil(root, 0);
}
public static int countPathsUtil(Node root, int currentSum) {
    if (root == null) {
        return 0;
    currentSum += root.data;
    if (root.left == null && root.right == null) {
        return 1;
    return countPathsUtil(root.left, currentSum) + countPathsUtil(root.right, currentSum);
public static Node insert(Node root, int key) {
    if (root == null) return new Node(key);
    if (key < root.data)
        root.left = insert(root.left, key);
    else
        root.right = insert(root.right, key);
    return root;
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Node root = null;
    System.out.print("Enter number of nodes: ");
    int n = sc.nextInt();
        System.out.println("Enter " + n + " node values:");
        for (int i = 0; i < n; i++) {
            int val = sc.nextInt();
            root = insert(root, val);
        int totalPaths = countPaths(root);
        System.out.println("Total number of root-to-leaf paths: " + totalPaths);
For grid problem
import java.util.Scanner;
public class GridPaths {
    static long factorial(int num) {
        long result = 1;
        for (int i = 2; i <= num; i++)
            result *= i;
        return result;
    static long countPaths(int n, int m) {
        return factorial(n + m) / (factorial(n) * factorial(m));
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n (rows): ");
        int n = sc.nextInt();
        System.out.print("Enter m (columns): ");
        int m = sc.nextInt();
        long totalPaths = countPaths(n, m);
        System.out.println("Number of paths from (0,0) to (" + n + "," + m + "): " + totalPaths);
Enter n (rows): 2
Enter m (columns): 2
Number of paths from (0,0) to (2,2): 6
Set20
20a)
import java.util.Arrays;
import java.util.Scanner;
public class TripletCheckerDynamic {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of elements in the array:");
        int n = scanner.nextInt();
        int[] arr = new int[n];
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        findTriplet(arr);
}
public static void findTriplet(int[] arr) {
    Arrays.sort(arr); // Sort the array to use the two-pointer technique
    int n = arr.length;
    boolean found = false;
    for (int i = 0; i < n - 1; i++) { // Loop through each element as the third element
        int left = 0; // Left pointer starts from the beginning
        int right = n - 1; // Right pointer starts from the last element
        while (left < right) {
            // Check if arr[i] is the sum of arr[left] and arr[right]
            if (arr[i] == arr[left] + arr[right]) {
                System.out.println("Triplet found: " + arr[left] + ", " + arr[right] + ", " + arr[i]);
                found = true;
                break; // Stop after finding the first triplet
            } else if (arr[left] + arr[right] < arr[i]) {
                left++; // Move left pointer to the right if sum is less than arr[i]
            } else {
                right--; // Move right pointer to the left if sum is greater than arr[i]
        if (found) break; // Stop iterating if a triplet is found
    if (!found) {
     System.out.println("No triplet found where the sum of two elements equals the third
element.");
Brute forcemethod
import java.util.Scanner;
public class TripletCheckerDynamic
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of elements in the array:");
        int n = scanner.nextInt();
        int[] arr = new int[n];
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        checkTriplet(arr);
    public static void checkTriplet(int[] arr) {
        boolean found = false;
        int length = arr.length;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
              for (int k = 0; k < length; k++) {
                    if (k != i && k != j && arr[i] + arr[j] == arr[k]) {
                        System.out.println(arr[i] + ", " + arr[j] + ", " + arr[k]);
                        found = true;
                        return; // Stop after finding the first triplet
        if (!found) {
            System.out.println("Triplet not exists");
Set 40 a
import java.util.Scanner;
public class StockTrading {
    public static int maxProfit(int[] prices, int fee) {
        // If there are no prices or only one price, no transaction can be made
        if (prices == null || prices.length <= 1) {
            return 0;
        }
    int cash = 0; // Maximum profit when not holding a stock
    int hold = -prices[0]; // Maximum profit when holding a stock
    for (int i = 1; i < prices.length; i++) {
        // Update cash: Either we don't sell or we sell after buying
        cash = Math.max(cash, hold + prices[i] - fee);
        // Update hold: Either we don't buy or we buy after selling previously held stock
        hold = Math.max(hold, cash - prices[i]);
    return cash; // The maximum profit is when we are not holding any stock
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the number of days:");
    int n = scanner.nextInt();
    int[] prices = new int[n];
    System.out.println("Enter the stock prices for each day:");
    for (int i = 0; i < n; i++) {
        prices[i] = scanner.nextInt();
    System.out.println("Enter the transaction fee:");
    int fee = scanner.nextInt();
        int profit = maxProfit(prices, fee);
        System.out.println("Maximum profit with transaction fee: " + profit);
Another method
import java.util.Scanner;
import java.util.Locale;
public class StockTrader {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in).useLocale(Locale.US); // Ensure decimal works with
periods
        String stockSymbol;
        int quantity=0;
        double purchasePrice = 0.0;
        boolean hasStock = false;
        System.out.println("Simple Stock Trading Simulation");
        while (true) {
          System.out.println("\nOptions:");
          System.out.println("1. Buy Stock");
          System.out.println("2. Sell Stock");
          System.out.println("3. Exit");
          System.out.print("Enter your choice: ");
          int choice = scanner.nextInt();
          scanner.nextLine(); // Consume newline
          switch (choice) {
        case 1:
           if (hasStock) {
               System.out.println("You already own stock. Sell before buying more.");
               break;
           System.out.print("Enter the stock symbol: ");
           stockSymbol = scanner.nextLine();
           System.out.print("Enter the quantity to buy: ");
           quantity = scanner.nextInt();
           System.out.print("Enter the purchase price per share: ");
           purchasePrice = scanner.nextDouble();
           scanner.nextLine(); // Consume newline
          System.out.println("Bought " + quantity + " shares of " + stockSymbol + " at $" +
purchasePrice + " per share.");
           hasStock = true;
           break;
        case 2:
           if (!hasStock) {
               System.out.println("You don't own any stock to sell.");
               break;
           System.out.print("Enter the selling price per share: ");
           double sellingPrice = scanner.nextDouble();
           scanner.nextLine(); // Consume newline
           // Debugging - Print values before calculating profit
           System.out.println("Debug - Purchase Price: " + purchasePrice);
           System.out.println("Debug - Selling Price: " + sellingPrice);
                  System.out.println("Debug - Quantity: " + quantity);
                  // Ensure the variables are valid before calculating profit
                  if (purchasePrice < 0 || sellingPrice < 0 || quantity < 1) {
                      System.out.println("Invalid input. Prices and quantity should be positive numbers.");
                      break;
                  // Calculate profit/loss
                  double profit = (sellingPrice - purchasePrice) * quantity;
                  System.out.println("Sold " + quantity + " shares of the stock for $" + sellingPrice + " per
share.");
                  System.out.println("Profit/Loss: $" + String.format("%.2f", profit)); // Format to 2 decimal
places
                  hasStock = false;
                  purchasePrice = 0.0; // Reset purchase price
                  break;
                case 3:
                  System.out.println("Exiting the simulation.");
                  scanner.close();
                  return;
                default:
                  System.out.println("Invalid choice. Please try again.");