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.

- Prepare
- Python
- Itertools
- Maximize It!
- Discussions

# Maximize It!

# Maximize It!

#### Sort by

recency

#### |

#### 1006 Discussions

#### |

Please Login in order to post a comment

k, l = list(map(int,input().split()))

z=[]

for i in range(k): z.append(list(map(int,input().split()))[1:])

import itertools product_result = list(itertools.product(*z))

final_list=[]

def square(x): return (x**2)

for i in product_result: s=(sum(list(map(square,i)))) % l final_list.append(s)

print(max(final_list))

Following @manuelalejandr26 and the key point explained by @ argxgd i.e.* "we have to take excatly 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.

from itertools import product

K, M = map(int,input().split())

N = (list(map(int, input().split()))[1:] for _ in range(K))

max_lst = [] for item in product(*N): S = 0 for val in item: S += val**2 S_max = S % M max_lst.append(S_max)

print(max(max_lst))

Did I misunderstood the problem??

What I did here is I took the max element out of all k lists provided, summed up the square value of the element(s) and as said applied modular with m. Am I missing something? Please explain if I misunderstood the problem. Thx.