I have come up with a sequence of steps to find the maximum product of y
positive numbers which add up to x
. But the program is highly inefficient.
Here's my code:
from itertools import product
from functools import reduce
from operator import mul
for i in range(int(input())): # <-- number of pairs of input
lgr = 1
k = set()
x, y = tuple(map(int, input().split())) # <-- the input pairs
p = product(range(1, x+1), repeat=y) # <-- gets the cross product
for i in p:
if sum(i) == x: # <-- checks if sum is equal to x
k.add(i) # <-- adds it to a set() to remove duplicates
for i in k:
tmp = reduce(mul, i, 1) # <-- multiplies the items in the tuple to get the largest
if tmp > lgr:
lgr = tmp
print(lgr)
But say for an input like 14 7
it just takes too long (around 20s). Is there a better way to do it?
Update 1:
I've managed to improve a bit by using combinations_with_replacement
and set & list comprehension
... but I believe it can be done better... any suggestions...?
from itertools import combinations_with_replacement
from functools import reduce
from operator import mul
for i in range(int(input())):
lgr = 1
x, y = tuple(map(int, input().split()))
k = {i for i in combinations_with_replacement(range(1, x+1), y) if sum(i) == x}
lgr = max([max(reduce(mul, i, 1), lgr) for i in k])
print(lgr)