Maximize It in python - HackerRank Solution
Problem :
S = ( f(X1) + f(X2) + ......+ f(Xk))%M
Note that you need to take exactly one element from each list, not necessarily
the largest element. You add the squares of the chosen elements and perform
the modulo operation. The maximum value that you can obtain, will be the
answer to the problem.
Input Format :
The first line contains 2 space separated integers k and m.
The next k lines each contains an integer Ni, denoting the number of elements in the ith list, followed by Ni space separated integers denoting the elements in the list.
The next k lines each contains an integer Ni, denoting the number of elements in the ith list, followed by Ni space separated integers denoting the elements in the list.
Constraints :
- 1 <= K <= 7
- 1 <= M <= 1000
- 1 <= Ni <= 7
- 1 <= magnitude of element in list <= 10^9
Output Format :
Output a single integer denoting the value Smax.
Sample Input :
3 1000 2 5 4 3 7 8 9 5 5 7 8 9 10
Sample Output :
206
Explanation :
Picking 5 from the 1st list, 9 from the 2nd list and 10 from the 3rd list
gives the maximum S value equal to (5^2 + 9^2 + 10^2)%1000 =206.
Solution :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # Maximize It in python - Hacker Rank Solution # Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT # Maximize It in python - Hacker Rank Solution START from itertools import * K, M = map(int, raw_input().split()) N = [] for _ in xrange(K): N.append(map(int, raw_input().split())[1:]) MAX = -1 for i in product(*N): MAX = max(sum(map(lambda x: x**2, i))%M, MAX) print MAX # Maximize It in python - Hacker Rank Solution END |
Disclaimer :-
the above hole problem statement is given by hackerrank.com but the solution is generated by the codeworld19 authority if any of the query regarding this post or website fill the following contact form thank you.
Latest update version:
from itertools import *
K, M = map(int, input().split())
mix = []
for _ in range(K):
# The first number indicates the size of space separated integer
# so we don't need it => start from index = 1
map_val = map(int, input().split())
lst = list(map_val)[1:]
mix.append(lst)
# https://www.geeksforgeeks.org/python-itertools-product/
N = list(product(*mix))
results = []
max_result = -1
for cartesian_arr in N:
sum_squared = sum(map(lambda x: x**2, cartesian_arr))
result = sum_squared % M
results.append(result)
#max_result = max(result, max_result)
max_result = max(results)
print(max_result)
from itertools import *
K, M = map(int, input().split())
N = []
for _ in range(K):
N.append(map(int, input().split()[1:]))
MAX = -1
for i in product(*N):
MAX = max(sum(map(lambda x: x**2, i))%M, MAX)
print (MAX)