## Interview Question for SDE-2s

Country: India
Interview Type: Written Test

Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming the card array is not already sorted..

``````def buy_cards(cards, cash):
if cards:
cards = sorted(cards)
cards = [0] + cards + [cards[-1] + cash]
res = 0
for n,m in zip(cards, cards[1:]):
if not cash:
break
d = int((-2*n - 3 + ((2*n+3)**2 + 8*(cash-n-1))**0.5)//2)
if d >= 0:
d = min(d, m-n-2)
res += d+1
cost = (d*d + d*(2*n+3) + 2*(n+1))//2
cash -= cost
return res

Output:

``````2
7``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

Won't a greedy solution suffice ? You iterate from 1 to the amount D , and for each number you check whether your sister already has it, if she does not , you check whether you can buy the card ( you maintain the amount you spend ) , if yes then add 1 to the answer.

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public class MaximumCardsToBuy {

static int buyMaximumCards(List<Integer> sisCards, int amount) {
if (amount == 0) {
return 0;
}
int result = 0;
int card = 1;
while (amount > 0 && card <= amount) {
if (!sisCards.contains(card) && amount >= card) {
result++;
amount -= card;
}
card++;
}
return result;
}

public static void main(String[] args) {
List<Integer> sisCards = Arrays.asList(2, 3, 5);
int amount = 7;

sisCards = Arrays.asList();
amount = 10;

sisCards = Arrays.asList(2, 3, 5, 10);
amount = 17;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public class MaximumCardsToBuy {

static int buyMaximumCards(List<Integer> sisCards, int amount) {
if (amount == 0) {
return 0;
}
int result = 0;
int card = 1;
while (amount > 0 && card <= amount) {
if (!sisCards.contains(card) && amount >= card) {
result++;
amount -= card;
}
card++;
}
return result;
}

public static void main(String[] args) {
List<Integer> sisCards = Arrays.asList(2, 3, 5);
int amount = 7;

sisCards = Arrays.asList();
amount = 10;

sisCards = Arrays.asList(2, 3, 5, 10);
amount = 17;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````static int buyMaximumCards(List<Integer> sisCards, int amount) {
if (amount == 0) {
return 0;
}
int result = 0;
int card = 1;
while (amount > 0 && card <= amount) {
if (!sisCards.contains(card) && amount >= card) {
result++;
amount -= card;
}
card++;
}
return result;
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.