code for You are given an array A containing weights of N pizzas. You have to eat…
- User
code for You are given an array A containing weights of N pizzas. You have to eat exactly 4 pizzas on each day.
When you eat pizzas of weights X, Y, Z and W where X >= Y >=Z>= W, you gain weight equal to Z.
Calculate the maximum total weight you can gain modulo 10^9+7, by eating the pizzas optimally each day.
Note: It is guaranteed that N is a multiple of 4.
Input Format
The first line contains an integer, N, denoting the number of elements in A.
Each line i of the N subsequent lines (where 0 < i < N) contains an integer describing A[i].
Constraints
1 <= N <= 10^5
1 <= A[ i]<= 10^5
Sample Test Cases
Case 1
Input:
8
1
3
4
1
5
1
5
3
Output:
5
Explanation:
Pizza weights are [1,3,4,1,5,1,5,3]. You can eat [1,1,1,3] and [3,4,5,5] in batches and gain 1 + 4 = 5 weight
Sample code
def totalWeight(A):
Write your code here
def main():
N = int(input())
A= [None]*N
for j in range(N):
A[j] = int(input())
result = totalWeight(A);
print(result)
if name == main":
main()
- Assistant
To solve the problem, we need to group the pizza weights into sets of four and maximize the total weight gained, which is determined by the third heaviest pizza in each set (i.e., the weight of the pizza when sorted in non-increasing order).
The optimal strategy is to sort the pizza weights in descending order, then take groups of four from the sorted list. The third pizza in each group of four will contribute to the total gain.
Here's the code that implements this logic:
python