Created
December 24, 2020 00:07
-
-
Save jeb2239/73d4b9e0d8b6bd27be6178b17347fb8e to your computer and use it in GitHub Desktop.
somequestion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Let’s say N ppl go on a trip, each spend some amount of money. Write a function to print out the how to split the money evenly, and minimize the number of transactions. | |
assumptions | |
N > 1 | |
input int/dec | |
time: NlogN | |
space: O(1) | |
min. # of transactions: N-1 | |
Input: | |
0 1 2 3 | |
[3,5,9,7] 24/4 = 6 => [6,6,6,6] 5=>give 1 to 7 = [3,6,6,9] 3 gives 3 to 9 =>[6666] 2tx | |
[0,1,2,3] | |
[(-3,0),(-1,1),(3,2),(1,3)] | |
N=4 | |
#tx = 2 | |
25 25 24 | |
[1 1 2 | 100] 26 | |
[-25,-25,-24,74] | |
0 1 2 3 | |
0 pays 3 $51 | |
1 pays 3 $51 | |
2 pays 3 $52 | |
[-74,74] | |
person 1 pay person 2 $1. | |
do the operation in order from distance from target | |
person 0 pays person3 $5. | |
person 1 pays person2 $2.50 | |
''' | |
def splitMoney(arr): | |
if len(arr)==0: | |
print('Fail') | |
return | |
tupleList=[] | |
for k,v in enumerate(arr): | |
tupleList.append((v,k)) | |
tupleList.sort() | |
target=sum(arr)/len(arr) | |
person_to_pay=len(arr)-1 | |
for i,pair in enumerate(tupleList): | |
amt,origIdx=pair | |
if i>=person_to_pay: | |
break | |
topay=target-amt | |
arr[origIdx]=topay | |
print('person {} pays person {} ${}'.format(origIdx,tupleList[person_to_pay][1],topay)) | |
if topay < 0: | |
person_to_pay-=1 | |
return | |
cases=[[3,5,9,7],[1,1,2,100],[0],[10.0, 9.99],[100,100,100,1],[2.50,5.00]] | |
for case in cases: | |
print('Case',case) | |
splitMoney(case) | |
# | |
# Your previous Plain Text content is preserved below: | |
# | |
# Welcome to your interviewing.io interview. | |
# | |
# Once you and your partner have joined, a voice call will start automatically. | |
# | |
# Use the language dropdown near the top right to select the language you would like to use. | |
# | |
# You can run code by hitting the 'Run' button near the top left. | |
# | |
# Enjoy your interview! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment