Problem: Given an array of integers inputs and an integer output, return an array of non-negative integers weights such that the sum of the element-wise product of inputs and weights equals output and the sum of the elements in weights is minimized. Return null (or equivalent) if no solution exists.
Example inputs and outputs:
calculateWeights([2, 4, 0, 6], 24)outputs[0, 0, 0, 4].calculateWeights([-6, -3, 5], -17)outputs[4, 1, 2].calculateWeights([-5, -3, 4, 6], 35)outputs either[0, 1, 2, 5]or[1, 0, 1, 6].calculateWeights([-5, -3, 0], 10)outputsnull.calculateWeights([2, 4, 6], 15)outputsnull.
I am looking for a solution with the best-case time complexity for such a problem. If this is not possible to determine, then I would really appreciate one with a significantly better time complexity than the below brute-force method, which seems to work as far as I can tell. Please feel free to use any language that is comfortable for you or pseudocode.
from itertools import product
from typing import Optional, List
def calculate_weights(inputs: List[int], output: int) -> Optional[List[int]]:
n = len(inputs)
# Generate all possible combinations of weights
possible_weights = product(range(abs(output) + 1), repeat = n)
result = None
min_weight_sum = float("inf")
for weights in possible_weights:
# Check if the sum of the products of the inputs and weights is equal to the output and is optimal
if sum(inputs[i] * weights[i] for i in range(n)) == output and sum(weights) < min_weight_sum:
min_weight_sum = sum(weights)
result = weights
# Return the optimal weights if found or None otherwise
return result
If it helps in finding a better solution, you can assume that there exists a minimum and maximum value for integers. If it helps in finding a better solution, you can additionally assume that such bounds are the common -2147483648 to 2147483647.
weightswith the sum of the elements inweightsbeing0, then1, etc., all the way up toabs(output)and returns as soon as a single solution is found since we are going up by the sum of the elements inweights. I'm leaving the current code in the question, though, as it is shorter and gets the point across. Additionally, this optimized brute-force solution is still nowhere near a good time complexity.