Maximize It!

  • + 3 comments

    Following @manuelalejandr26 and the key point explained by @argxgd i.e.* " we have to take exactly one element from each list but not neccessarily the largest one. Although our target is to get the max value of sum S. Since we are dealing with modulo operator, a smaller element might yield a higher modulo then a bigger and this entirely depends on the value of M. "*

    At first we might naively select the max integer from each list. However, this will not work, as explained above. We can therefore calculate all possible outcomes, i.e. sum(x => x ** 2)%M, from all of the possible single selections from each list). Once we have all of the possible outcomes as a list, we can print the max value.

    The important tool is itertools.product. Given a list of integers. we can then generate a list of all possible permutations, selecting one item from each list. We can then use list comprehensions to apply the formula (sum(x => x ** 2)%M for each permutation.

    >>> list(product(*[[1, 2], [3, 4]])) # use * to unpack the list
    [(1, 3), (1, 4), (2, 3), (2, 4)] # all possible permutations, each as a tuple
    
    from itertools import product
    
    K, M = map(int, input().split())
    
    lists = [input().split()[1:] for _ in range(K)]
    possibles = product(*lists)
    moduli = [sum(map(lambda x: int(x) **2, item))%M for item in possibles]
    print(max(moduli))