We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

defbonetrousle(n,k,b):"""Find b distinct integers in [0,...,k] that sum to n."""# Define these convenient variables:N=n-b*(b+1)//2d=k-b# For a solution to exist, n must lie between the sum of first b boxes and the last b boxesif(N<0)or(N>b*d):return[-1]elifN==0:#edgecasewhend==0return[*range(1,b+1)]else:# Imagine starting with first b boxes. While keeping the sum below n, replace b->k, (b-1)->(k-1), .... Each shift adds d to the total. Finally add the missing balance to the "next" (b-i) term. (i.e. the largest value in [1,2,..b] that didn't get shifted.)q,r=N//d, N % d# Take care of edge case with b-q+r==0 mid=[]if(b==q-r)else[b-q+r]return[*range(1,b-q)]+mid+[*range(k,k-q,-1)]

Cookie support is required to access HackerRank

Seems like cookies are disabled on this browser, please enable them to open this website

## Bonetrousle

You are viewing a single comment's thread. Return to all comments â†’

python3: pure math solution