# your code goes here
def kth( a, b, k) :
M = len ( a)
N = len ( b)
( ia, ib) = M-1 , N-1 #0 based arrays
# we need this for lookback
nottakenindices = ( 0 , 0 ) # could be any value
nottakensum = float ( '-inf' )
for i in range ( k-1 ) :
optionone = a[ ia] +b[ ib-1 ]
optiontwo = a[ ia-1 ] +b[ ib]
biggest = max ( ( optionone, optiontwo) )
#first deal with look behind
if nottakensum > biggest:
if optionone == biggest:
newnottakenindices = ( ia, ib-1 )
else : newnottakenindices = ( ia-1 , ib)
ia, ib = nottakenindices
nottakensum = biggest
nottakenindices = newnottakenindices
elif optionone > optiontwo:
#then choose the first option as our next pair
nottakensum, nottakenindices = optiontwo, ( ia-1 , ib)
ib-= 1
elif optionone < optiontwo: # choose the second
nottakensum, nottakenindices = optionone, ( ia, ib-1 )
ia-= 1
#next two cases apply if options are equal
elif a[ ia] > b[ ib] :# drop the smallest
nottakensum, nottakenindices = optiontwo, ( ia-1 , ib)
ib-= 1
else : # might be equal or not - we can choose arbitrarily if equal
nottakensum, nottakenindices = optionone, ( ia, ib-1 )
ia-= 1
#+2 - one for zero-based, one for skipping the 1st largest
data = ( i+2 , a[ ia] , b[ ib] , a[ ia] +b[ ib] , ia, ib)
narrative = "%sth largest pair is %s+%s=%s, with indices (%s,%s)" % data
print ( narrative) #this will work in both versions
return data, narrative
a, b = [ 2 , 3 , 5 , 8 , 13 ] , [ 4 , 8 , 12 , 16 ]
kth( a, b, 3 )
a = [ 1 , 2 , 53 ] ; b = [ 66 , 67 , 68 ]
kth( a, b, 3 )
a, b = [ 2 , 3 , 5 , 8 , 13 ] , [ 4 , 8 , 12 , 16 ]
kth( a, b, 4 )
IyB5b3VyIGNvZGUgZ29lcyBoZXJlCgpkZWYga3RoKGEsYixrKToKICAgIE0gPSBsZW4oYSkKICAgIE4gPSBsZW4oYikKICAgIChpYSxpYikgPSBNLTEsTi0xICMwIGJhc2VkIGFycmF5cwogICAgIyB3ZSBuZWVkIHRoaXMgZm9yIGxvb2tiYWNrCiAgICBub3R0YWtlbmluZGljZXMgPSAoMCwwKSAjIGNvdWxkIGJlIGFueSB2YWx1ZQogICAgbm90dGFrZW5zdW0gPSBmbG9hdCgnLWluZicpCiAgICBmb3IgaSBpbiByYW5nZShrLTEpOgogICAgICAgIG9wdGlvbm9uZSA9IGFbaWFdK2JbaWItMV0KICAgICAgICBvcHRpb250d28gPSBhW2lhLTFdK2JbaWJdCiAgICAgICAgYmlnZ2VzdCA9IG1heCgob3B0aW9ub25lLG9wdGlvbnR3bykpCiAgICAgICAgI2ZpcnN0IGRlYWwgd2l0aCBsb29rIGJlaGluZAogICAgICAgIGlmIG5vdHRha2Vuc3VtID4gYmlnZ2VzdDoKICAgICAgICAgICBpZiBvcHRpb25vbmUgPT0gYmlnZ2VzdDoKICAgICAgICAgICAgICAgbmV3bm90dGFrZW5pbmRpY2VzID0gKGlhLGliLTEpCiAgICAgICAgICAgZWxzZTogbmV3bm90dGFrZW5pbmRpY2VzID0gKGlhLTEsaWIpCiAgICAgICAgICAgaWEsaWIgPSBub3R0YWtlbmluZGljZXMKICAgICAgICAgICBub3R0YWtlbnN1bSA9IGJpZ2dlc3QKICAgICAgICAgICBub3R0YWtlbmluZGljZXMgPSBuZXdub3R0YWtlbmluZGljZXMKICAgICAgICBlbGlmIG9wdGlvbm9uZSA+IG9wdGlvbnR3bzogCiAgICAgICAgICAgI3RoZW4gY2hvb3NlIHRoZSBmaXJzdCBvcHRpb24gYXMgb3VyIG5leHQgcGFpcgogICAgICAgICAgIG5vdHRha2Vuc3VtLG5vdHRha2VuaW5kaWNlcyA9IG9wdGlvbnR3bywoaWEtMSxpYikKICAgICAgICAgICBpYi09MQogICAgICAgIGVsaWYgb3B0aW9ub25lIDwgb3B0aW9udHdvOiAjIGNob29zZSB0aGUgc2Vjb25kCiAgICAgICAgICAgbm90dGFrZW5zdW0sbm90dGFrZW5pbmRpY2VzID0gb3B0aW9ub25lLChpYSxpYi0xKQogICAgICAgICAgIGlhLT0xCiAgICAgICAgI25le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