Let the array contain the numbers written on the cards. We initialize pointers i = 0 at the beginning of the array and j = n - 1 at the end of the array.
On each turn, a player takes the card with the maximum value max (m[i], m[j]), after which the card is removed from the table (perform the operation i++ if the card is chosen, and j-- if the card is chosen). For each player, we keep track of the sum of the selected cards in two variables. The process continues until all cards are removed from the table, that is, until the pointers and meet.
Example
The game will proceed as follows.
Algorithm realization
Declare the arrays. The sum of the numbers on the cards collected by Huseyn and Yaroslav will be stored in and , respectively.
int m[10001], res[2];Read the input data.
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &m[i]);Set the pointers i = 0 and j = n - 1.
i = 0; j = n - 1;The players take turns, making moves in total. Huseyn takes turns for even , and Yaroslav takes turns for odd . Accordingly, Huseyn's sum will accumulate in , and Yaroslav's sum will accumulate in .
for (k = 0; k < n; k++)
{On each turn, the player chooses the card with the maximum value max(m[i], m[j]).
if (m[i] > m[j])
res[k % 2] += m[i++];
else
res[k % 2] += m[j--]; ;
}Print the answer.
printf("%d %d\n", res[0], res[1]);Python realization
Read the input data.
n = int(input())
m = list(map(int, input().split()))Set the pointers i = 0 and j = n - 1.
i, j = 0, n – 1The sum of the numbers on the cards collected by Huseyn and Yaroslav will be stored in and , respectively.
res = [0, 0]The players take turns, making moves in total. Huseyn takes turns for even , and Yaroslav takes turns for odd . Accordingly, Huseyn's sum will accumulate in , and Yaroslav's sum will accumulate in .
for k in range(n):On each turn, the player chooses the card with the maximum value max(m[i], m[j]).
if m[i] > m[j]:
res[k % 2] += m[i]
i += 1
else:
res[k % 2] += m[j]
j -= 1Print the answer.
print(res[0], res[1])