Home > front end >  find the smallest amount of numbers upto n that sum to m no repetitions
find the smallest amount of numbers upto n that sum to m no repetitions

Time:10-12

some clarification for when there is more than one solution eg. when n = 5 m = 10 both 2,3,5 and 1,4,5 are valid. the second is the correct solution since it has the larger numbers

I've already written code that does this but I can't get it to run fast enough

edit: specifically I need it to run in under 5 seconds and n = 86879 and m = 3131840392 doesn't run fast enough

n, m = map(int,input().split())
soln = []
for i in range(n,0,-1):
    if(sum(soln)   i <= m):
        soln.append(i)
    
soln.reverse()
print(len(soln))
print(soln[0],end="")
for i in range(1,len(soln)):
    print("",soln[i],end = "")
print("")

CodePudding user response:

You are actually on the right track: Just sum up n n-1 n-2 ... until that sum hits m. The only problem is the sum, which makes your algorithm O(n²). If you just keep track of the running sum in a second variable, it is O(n) and much faster. Also, once the next element does not "fit" anymore, you can just add the remainder and break from the loop.

n = 86879
m = 3131840392

soln = []
res = 0
for i in range(n, 0, -1):
    if res   i <= m:
        soln.append(i)
        res  = i
    elif res   i > m:
        soln.append(m - res)
        break

print(soln)
print(len(soln))
  • Related