Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I had recently got the following question in an interview for a software position. As far as I can remember, it goes like : There are n houses at a stretch represented by an array A[1...n] containing their respective positions in sorted order.
For example, consider the array A[] = {1,3,5,10}. Each of the houses has a single gold coin, and you, being a thief, want to steal gold coins from k houses.
But there is a constraint: If I select k houses, then the difference in distance between any two of the selected houses must be more than k.
In the above example: If k = 3, then I can select houses with positions: 1,5,10. If k = 4, I cannot select 4 houses based on the above constraint.
I want to maximize k.
In the above example, k = 3 is the expected answer.
Currently, I have a brute force naive algorithm where for every value of k starting from 1, I check if that many number of house selections are possible. If possible, I increment kand do the same thing again.
Can you help me solve it more efficiently?
Idea: Binary search the value of k.
Let the array be sorted
low=1
high=min(n,sqrt(a[n] - a[1]))
while(low<=high)
mid = (low+high)/2
if( mid is a valid answer)
low=mid+1
else
high=mid-1
return high
Now to check if a given value of mid is a valid answer, you just use the greedy strategy:
Pick 1st house, then keep choosing next house which is at least mid distance away from last chosen house and if at the end, the number of robbed house are more then or equal to mid, then a valid theft is possible otherwise not.
Complexity: O(n log n)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
if there are more than K customers present in the hotel at any given moment ,then period of time is called P period.
Task is to determine the P period
Input format
first line contains n and k and next n lines contain check-in and check-out time of the ith customer
Test Case:
3 2
5 8
2 4
3 9
Output:4
If I am not wrong we have to find the time at which more than K customers present at the moment.
my code
def hotel(n,k,A):
count=0
dp=[1]*n
for i in range(n):
I1=A[i][0]
o1=A[i][1]
time=[]
for j in range(i+1,n):
I2=A[j][0]
o2=A[j][1]
if I1>=I2 and I1<o2:
dp[i]=dp[i]+1
if o1<=o2:
time.append(o1-I1)
else:
time.append(o2-I1)
elif I1<I2 and o1>I2:
dp[i]=dp[i]+1
if o1>o2:
time.append(o2-I2)
else:
time.append(o1-I2)
if dp[i]>=k:
count+=sum(time)
return count
Problem it showing wrong answer with code
can anyone help.
The sample result (4) suggests that we are looking for the total number of days where at least K (not more than) customers are present. The problem statement also doesn't specify if the check out day is included or excluded from the periods (which gives the same answer for this data but may differ on other samples).
In any case, you can compute these values using list comprehensions and sums:
n = 3
K = 2
A = [(5,8),(2,4),(3,9)]
checkIns,checkOuts = zip(*A)
firstDay = min(checkIns)
lastDay = max(checkOuts)
counts = [ sum(day in range(inTime,outTime) for inTime,outTime in A)
for day in range(firstDay,lastDay+1) ]
P = sum(count >= K for count in counts)
print(P) # 4
The counts list is built by going through every possible day and counting, for each day, how many customers were present. Counting customers for a given day goes through the check-in/check-out times (in A) to check if that day is within the customer's presence period.
note: range(inTime,outTime) above assumes that check-out days are excluded. Change it to range(inTime,outTime+1) if they are to be included
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a problem to get the value from first list based on second list. We can assume that we have an election. First list is the list of candidates, second list is the list of votes for this candidates.
candidatesList = [1,2,3,4]
voteList = [2,4,4,1]
One of the rules of election is that, if two or more candidates got same amount of votes then the winner is a candidate with lower number. In this case above output should be 2. I can change data structures but the output must be same.
Simplest way
candidatesList[voteList.index(max(voteList))]
max(voteList) gets you the max of the votes.
voteList.index(max(voteList)) gets you the index of the highest vote from the right hand side.
candidatesList[...] gets you the person
As far as I understand, this might be what you are looking for:
import numpy as np
candidates_list = [1,2,3,4]
vote_list = [2,4,4,1]
best_candidate_index = np.argmax(vote_list)
print("Best candidate", candidates_list[best_candidate_index])
Create dataframe, sort by ['voteList','candidatesList'] and use the top row.
d = dict(candidatesList = [1,2,3,4], voteList = [2,4,4,1])
pd.DataFrame(d).sort_values(by=['voteList','candidatesList'], ascending=[False,True]).candidatesList.iloc[0]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Question: Antonia and David are playing a game. Each player starts with 100 points. The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player. Write a program to output the final scores and the winner
Input Specification The first line of input contains the integer n (1 ≤ n ≤ 15), which is the number of rounds that will be played. On each of the next n lines, will be two integers: the roll of Antonia for that round, followed by a space, followed by the roll of David for that round. Each roll will be an integer between 1 and 6 (inclusive). Output Specification The output will consist of two lines. On the first line, output the number of points that Antonia has after all rounds have been played. On the second line, output the number of points that David has after all rounds have been played.
One of my many problems is making the program list the correct number of inputs the first input specifies.
Here is what I have so far:
I know I only asked for one thing specifically, but can anyone complete this challenge so I can see what I can add to my program
Because it is a homework question, you really should try to it yourself first. With this being said, I will give you hints but I will not give you a full working program - I hope you can understand my reasoning for this.
To start, this problem definitely calls for some type of iteration as rolling a dice for n amount of times is repetitive. Whether you choose a for loop or a while loop is up to you - in this example I use a while loop. After getting the amount of rounds (don't forget to convert the user input into int), you can write something like this:
while rounds > 0:
# simulate rolling here
rounds -= 1
Rolling a dice is a random action - there is a 1/n chance to roll a number where n is the number of sides on the dice. I would suggest creating a list of all possibilities:
dice = [1,2,3,4,5,6]
And then use choice() from the random module to select a random item from this list.
from random import choice
david_roll = choice(dice)
antonia_roll = choice(dice)
Now that you have the values of each roll, you can just perform some simple comparison on the rolls:
if david_roll > antonia_roll:
# modify scores accordingly
elif david_roll < antonia_roll:
# modify scores accordingly
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to randomly generate an array of integers of range between -10^7 to 10^7 such that there exists a sub-array with a sum of zero.
For example : 7 6 4 8 -4 -8
1<=Size of array<=10^5
I am able to do it using brute-force but it is taking a lot of time as I have to generate very big such arrays. Is there any efficient way of achieving this using python or c++?
Edit: Actually I want to generate a lot of such arrays with different scenarios. I am generating these arrays as testcases for a problem to determine whether any given array of positive and negative integers contain a sub-array with zero sum.
Tried brute force code:
import random
N = random.randint(10,100)
mylist = []
for i in xrange(1,N):
mylist.append(random.randint(-100,100))
list2 = [1,-1]
mylist = mylist[1:N-2] + list2 + mylist[N-2:N]
print mylist
So I have to manually tweak it a lot.
Thanks!
The answer depends on how random you want your array to be. Like some of the commenters mentioned, you can always include a zero and are thus guaranteed to have a subarray with sum of zero. I thought it would be helpful to your eventual solution, so I want to mention that you can check if an array has a subarray with sum of zero in O(N^2) time.
def array_has_zerosubarray( A ):
for _begin in xrange(0,len(A)-1):
for _end in xrange(_begin+1,len(A)):
sum = 0
for ai in range(_begin,_end):
sum = sum + A[ai]
if sum==0:
return True
return False
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have question and a solution. But the solution doesnt seem to be satisfy all test cases :
Question:
variable N denotes the naming boundary(0,N-1)
variable K denotes the number of test cases
each test case is of format (x,y)...(a,b)
such that if (x,y) is given x,y belongs to same class
and if (x,y) and (y,z) is given x,y,z belongs to same class
The output should be number of possible ways of selecting 2 items from different class
Solution :
inp=raw_input()
inp1=inp.split(' ')
n=int(inp1[0])
k=int(inp1[1])
classes=[[]for i in xrange(0,n)]
no_classes=0
def in_list(c):
for i in range(0,no_classes):
if c in classes[i]:
return i;
return -1
for i in range(0,k):
inp=raw_input()
inp1=inp.split(' ')
c1=int(inp1[0])
c2=int(inp1[1])
l1=in_list(c1)
l2=in_list(c2)
if l1<0 and l2<0:
classes[no_classes].append(c1)
classes[no_classes].append(c2)
no_classes+=1
elif l1>=0 and l2<0:
classes[l1].append(c2)
elif l2>=0 and l1<0 :
classes[l2].append(c1)
elif l1>=0 and l2>=0 and l1!=l2:
classes[l1]=list(set(classes[l1]+classes[l2]))
del classes[l2]
no_classes-=1
tot_combntns=0;
for i in range(0,no_classes):
for j in range(i+1,no_classes):
tot_combntns=tot_combntns+len(classes[i])*len(classes[j])
print tot_combntns
Sample test case :
6 3
0 1
2 3
4 5
ans : 12
5 4
0 1
1 2
2 3
3 4
ans = 0 because there is only one class(0,1,2,3,4)
But I am not sure this solution satisfies all test cases
Because this is a practice programming challenge, I won't get you the answer. I will tell you enough to figure it out if you are competent. I'm leaving it at what I consider a reasonable difficulty level. If you're capable of creating objects, performing recursion, etc, then it should be straightforward. If you're not capable of that, then failing this programming challenge is a sign that you need to learn more basics.
If you have a group of n items, the number of ways of picking a pair from them is n*(n-1)/2. The number of ways of picking a pair from different classes is the number of ways of picking a pair minus, for each class, the number of ways of picking a pair from that class. The challenge is, therefore, to find the classes and count each one.
Figuring out that two elements are in the same class can involve many possible chains of reasoning. For instance the rules (a, b), (x,y), (b, y) imply that a and x are in the same class. How do you efficiently go through all possible reasoning chains? A simple and efficient method is to create an object that can take any element and map it to the smallest known member of its class. (Under the hood it suffices for it to map every element that is not minimal to a smaller known one, and lazily figure out the smallest known one on demand.)
Figuring out how to implement that object I leave as an exercise. As is, once you have it, figuring out how to count how many are in each class.