0% found this document useful (0 votes)
5 views11 pages

Ass 9 Advcod

The document contains three coding problems: 'LeetCode Store', 'Recover Binary Search Tree', and 'Ambiguous Dominoes', each accompanied by example inputs and outputs. The first problem involves calculating the lowest price for items considering special offers, the second focuses on recovering a binary search tree with two swapped nodes, and the third requires generating distinct tilings of dominoes on a grid. Each problem includes Java code implementations to solve the respective tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Ass 9 Advcod

The document contains three coding problems: 'LeetCode Store', 'Recover Binary Search Tree', and 'Ambiguous Dominoes', each accompanied by example inputs and outputs. The first problem involves calculating the lowest price for items considering special offers, the second focuses on recovering a binary search tree with two swapped nodes, and the third requires generating distinct tilings of dominoes on a grid. Each problem includes Java code implementations to solve the respective tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Advanced Coding

ASSIGNMENT - 9

Q. LeetCode Store
In LeetCode Store, there are n items to sell. Each item has a price.
However, there are some special offers, and a special offer consists of
one or more different kinds of items with a sale price.
You are given an integer array price where price[i] is the price of
the ith item, and an integer array needs where needs[i] is the number
of pieces of the ith item you want to buy.
You are also given an array special where special[i] is of size n +
1 where special[i][j] is the number of pieces of the j th item in
the ith offer and special[i][n] (i.e., the last integer in the array) is the
price of the ith offer.
Return the lowest price you have to pay for exactly certain items as
given, where you could make optimal use of the special offers. You
are not allowed to buy more items than you want, even if that would
lower the overall price. You could use any of the special offers as
many times as you want.

Example 1:
Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
Explanation: There are two kinds of items, A and B. Their prices are
$2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B
(special offer #2), and $4 for 2A.

Constraints:
 n == price.length == needs.length
 1 <= n <= 6
 0 <= price[i], needs[i] <= 10
 1 <= special.length <= 100
 special[i].length == n + 1
 0 <= special[i][j] <= 50
 The input is generated that at least one of special[i][j] is non-zero
for 0 <= j <= n - 1.

Code:

import java.util.*;

public class ShoppingOffers {


public int shoppingOffers(List<Integer> price, List<List<Integer>>
special, List<Integer> needs) {
return dfs(price, special, needs, new HashMap<>());
}

private int dfs(List<Integer> price, List<List<Integer>> special,


List<Integer> needs, Map<List<Integer>, Integer> memo) {
if (memo.containsKey(needs)) {
return memo.get(needs);
}

// Calculate cost without using any special offers


int minCost = directPurchase(price, needs);

// Try every special offer


for (List<Integer> offer : special) {
List<Integer> newNeeds = new ArrayList<>(needs);
boolean validOffer = true;

for (int i = 0; i < needs.size(); i++) {


newNeeds.set(i, newNeeds.get(i) - offer.get(i));
if (newNeeds.get(i) < 0) {
validOffer = false; // Cannot use offer as it exceeds
needs
break;
}
}

if (validOffer) {
minCost = Math.min(minCost, offer.get(needs.size()) +
dfs(price, special, newNeeds, memo));
}
}
memo.put(needs, minCost);
return minCost;
}

private int directPurchase(List<Integer> price, List<Integer> needs) {


int cost = 0;
for (int i = 0; i < price.size(); i++) {
cost += price.get(i) * needs.get(i);
}
return cost;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
ShoppingOffers solution = new ShoppingOffers();

// Read number of items


System.out.print("Enter number of items: ");
int n = scanner.nextInt();

// Read price array


List<Integer> price = new ArrayList<>();
System.out.println("Enter price of each item:");
for (int i = 0; i < n; i++) {
price.add(scanner.nextInt());
}

// Read number of special offers


System.out.print("Enter number of special offers: ");
int m = scanner.nextInt();
List<List<Integer>> special = new ArrayList<>();

System.out.println("Enter each special offer (n items + 1 offer


price):");
for (int i = 0; i < m; i++) {
List<Integer> offer = new ArrayList<>();
for (int j = 0; j <= n; j++) { // n items + 1 for offer price
offer.add(scanner.nextInt());
}
special.add(offer);
}

// Read needs array


List<Integer> needs = new ArrayList<>();
System.out.println("Enter the required quantity of each item:");
for (int i = 0; i < n; i++) {
needs.add(scanner.nextInt());
}

// Compute and print the minimum cost


int result = solution.shoppingOffers(price, special, needs);
System.out.println("Minimum cost to buy items: " + result);
scanner.close();
}
}
Q. Recover Binary Search Tree
You are given the root of a binary search tree (BST), where the values
of exactly two nodes of the tree were swapped by mistake. Recover
the tree without changing its structure.

Example 1:

Input: root = [1,3,null,null,2]


Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1
and 3 makes the BST valid.
Code:

import java.util.*;

class TreeNode {
int val;
TreeNode left, right;

TreeNode(int val) {
this.val = val;
}
}

public class Main { // Main class for online compilers

TreeNode first = null, second = null, prev = new


TreeNode(Integer.MIN_VALUE);

// Function to recover the BST


public void recoverTree(TreeNode root) {
inOrder(root);
// Swap the values of the two incorrect nodes
int temp = first.val;
first.val = second.val;
second.val = temp;
}

private void inOrder(TreeNode root) {


if (root == null) return;

inOrder(root.left);

// Find misplaced nodes


if (first == null && prev.val > root.val) {
first = prev; // First incorrect node
}
if (first != null && prev.val > root.val) {
second = root; // Second incorrect node
}
prev = root;

inOrder(root.right);
}

// Helper function to print in-order traversal of BST


public void printInOrder(TreeNode root) {
if (root == null) return;
printInOrder(root.left);
System.out.print(root.val + " ");
printInOrder(root.right);
}
// Main method to test the implementation
public static void main(String[] args) {
Main bst = new Main(); // Create an instance

// Construct an incorrect BST: [3,1,4,null,null,2]


TreeNode root = new TreeNode(3);
root.left = new TreeNode(1);
root.right = new TreeNode(4);
root.right.left = new TreeNode(2);

System.out.println("Before Recovery (Inorder Traversal):");


bst.printInOrder(root);
System.out.println();

// Recover BST
bst.recoverTree(root);

System.out.println("After Recovery (Inorder Traversal):");


bst.printInOrder(root);
System.out.println();
}
}

output
Q. Ambiguous Dominoes

Polycarp and Monocarp are both solving the same puzzle with
dominoes. They are given the same set of nn dominoes, the ii-th of
which contains two numbers xixi and yiyi. They are also both given
the same mm by kk grid of values aijaij such that m⋅k=2nm⋅k=2n.
The puzzle asks them to place the nn dominoes on the grid in such a
way that none of them overlap, and the values on each domino match
the aijaij values that domino covers. Dominoes can be rotated
arbitrarily before being placed on the grid, so the
domino (xi,yi)(xi,yi) is equivalent to the domino (yi,xi)(yi,xi).
They have both solved the puzzle, and compared their answers, but
noticed that not only did their solutions not match, but none of
the nn dominoes were in the same location in both solutions!
Formally, if two squares were covered by the same domino in
Polycarp's solution, they were covered by different dominoes in
Monocarp's solution. The diagram below shows one potential aa grid,
along with the two players' solutions.

Code:

import java.util.*;

public class AmbiguousDominoes {


static int n, m, k;
static List<int[]> dominos;
static int[][] grid;
static char[][] polycarp, monocarp;

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
n = sc.nextInt();
dominos = new ArrayList<>();

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


int x = sc.nextInt();
int y = sc.nextInt();
dominos.add(new int[]{x, y});
}
// Special case: If n = 1, return -1
if (n == 1) {
System.out.println("-1");
return;
}

// Step 1: Find m and k such that m * k = 2n


findGridDimensions();
if (m == -1) {
System.out.println("-1");
return;
}

// Step 2: Construct grid & assign numbers


constructGrid();

// Step 3: Generate two distinct tilings


createSolutions();

// Step 4: Output the results


printResults();
}

// Step 1: Find grid dimensions m, k such that m * k = 2n


static void findGridDimensions() {
for (int i = 1; i * i <= 2 * n; i++) {
if ((2 * n) % i == 0) {
m = i;
k = (2 * n) / i;
return;
}
}
m = -1; // No valid grid found
}

// Step 2: Construct the number grid


static void constructGrid() {
grid = new int[m][k];
int num = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < k; j++) {
grid[i][j] = num++;
}
}
}

// Step 3: Generate two distinct tilings


static void createSolutions() {
polycarp = new char[m][k];
monocarp = new char[m][k];
// First tiling - Horizontal Dominos
for (int i = 0; i < m; i++) {
for (int j = 0; j < k; j += 2) {
if (j + 1 < k) {
polycarp[i][j] = 'L';
polycarp[i][j + 1] = 'R';
}
}
}

// Second tiling - Vertical Dominos


for (int j = 0; j < k; j++) {
for (int i = 0; i < m; i += 2) {
if (i + 1 < m) {
monocarp[i][j] = 'U';
monocarp[i + 1][j] = 'D';
}
}
}
}

// Step 4: Print the results


static void printResults() {
System.out.println(m + " " + k);

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


for (int j = 0; j < k; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}

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


System.out.println(new String(polycarp[i]));
}

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


System.out.println(new String(monocarp[i]));
}
}
}
OUTPUT

You might also like