Open In App

Maximum amount of money that can be collected by a player in a game of coins

Last Updated : 10 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D array Arr[][] consisting of N rows and two persons A and B playing a game of alternate turns based on the following rules:

  • A row is chosen at random, where A can only take the leftmost remaining coin while B can only take the rightmost remaining coin in the chosen row.
  • The game ends when there are no coins left.

The task is to determine the maximum amount of money obtained by A.

 Examples:

Input: N = 2, Arr[][] = {{ 5, 2, 3, 4 }, { 1, 6 }}
Output: 8
Explanation: 
Row 1: 5, 2, 3, 4
Row 2: 1, 6
Operations:

  1. A takes the coin with value 5
  2. B takes the coin with value 4
  3. A takes the coin with value 2
  4. B takes the coin with value 3
  5. A takes the coin with value 1
  6. B takes the coin with value 6

Optimally, money collected by A = 5 + 2 + 1 = 8 
Money collected by B = 3 + 4 + 6 = 13

Input: N = 1, Arr[] = {{ 1, 2, 3 }}
Output : 3

  Approach: Follow the steps below to solve the problem

  1. In a game played with optimal strategy
  2. Initialize a variable, say amount, to store the money obtained by A.
  3. If N is even, A will collect the first half of the coins
  4. Otherwise, first, (N / 2) coins would be collected by A and last (N / 2) would be collected by B
  5. If N is odd, the coin at the middle can be collected by A or B, depending upon the sequence of moves.
  6. Store the coin at the middle of all odd sized rows in a variable, say mid_odd[].
  7. Sort the array mid_odd[] in descending order.
  8. Optimally, A would collect all coins at even indices of min_odd[]
  9. Finally, print the score of A.

Below is the implementation of the above approach:

C++




// CPP Program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to calculate the
// maximum amount collected by A
void find(int N,  vector<vector<int>>Arr)
{
     
    // Stores the money
    // obtained by A
    int amount = 0;
 
    // Stores mid elements
    // of odd sized rows
    vector<int> mid_odd;
    for(int i = 0; i < N; i++)
    {
 
        // Size of current row
        int siz = Arr[i].size();
 
        // Increase money collected by A
        for (int j = 0; j < siz / 2; j++)
            amount = amount + Arr[i][j];
 
        if(siz % 2 == 1)
            mid_odd.push_back(Arr[i][siz/2]);
    }
 
    // Add coins at even indices
    // to the amount collected by A
    sort(mid_odd.begin(),mid_odd.end());
 
    for(int i = 0; i < mid_odd.size(); i++)
        if (i % 2 == 0)
         amount = amount + mid_odd[i];
 
    // Print the amount
    cout<<amount<<endl;
 
}
 
// Driver Code
int main()
{
   int N = 2;
   vector<vector<int>>Arr{{5, 2, 3, 4}, {1, 6}};
 
   // Function call to calculate the
   // amount of coins collected by A
   find(N, Arr);
}
 
// This code is contributed by ipg2016107.


Java




// Java program to implement
// the above approach
import java.util.*;
class GFG
{
  
// Function to calculate the
// maximum amount collected by A
static void find(int N, int[][] Arr)
{
     
    // Stores the money
    // obtained by A
    int amount = 0;
 
    // Stores mid elements
    // of odd sized rows
    ArrayList<Integer> mid_odd
            = new ArrayList<Integer>();
    for(int i = 0; i < N; i++)
    {
 
        // Size of current row
        int siz = Arr[i].length;
 
        // Increase money collected by A
        for (int j = 0; j < siz / 2; j++)
            amount = amount + Arr[i][j];
 
        if(siz % 2 == 1)
            mid_odd.add(Arr[i][siz/2]);
    }
 
    // Add coins at even indices
    // to the amount collected by A
    Collections.sort(mid_odd);
     
    for(int i = 0; i < mid_odd.size(); i++){
        if (i % 2 == 0)
         amount = amount + mid_odd.get(i);
    }
 
    // Print the amount
    System.out.println(amount);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 2;
   int[][] Arr = {{5, 2, 3, 4}, {1, 6}};
 
   // Function call to calculate the
   // amount of coins collected by A
   find(N, Arr);
}
}
  
// This code is contributed by splevel62.


Python3




# Python Program to implement
# the above approach
 
# Function to calculate the
# maximum amount collected by A
 
 
def find(N, Arr):
 
    # Stores the money
    # obtained by A
    amount = 0
 
    # Stores mid elements
    # of odd sized rows
    mid_odd = []
 
    for i in range(N):
 
        # Size of current row
        siz = len(Arr[i])
 
        # Increase money collected by A
        for j in range(0, siz // 2):
            amount = amount + Arr[i][j]
 
        if(siz % 2 == 1):
            mid_odd.append(Arr[i][siz // 2])
 
    # Add coins at even indices
    # to the amount collected by A
    mid_odd.sort(reverse=True)
 
    for i in range(len(mid_odd)):
        if i % 2 == 0:
            amount = amount + mid_odd[i]
 
    # Print the amount
    print(amount)
 
 
# Driver Code
 
N = 2
Arr = [[5, 2, 3, 4], [1, 6]]
 
# Function call to calculate the
# amount of coins collected by A
find(N, Arr)


C#




// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to calculate the
  // maximum amount collected by A
  static void find(int N, List<List<int>> Arr)
  {
 
    // Stores the money
    // obtained by A
    int amount = 0;
 
    // Stores mid elements
    // of odd sized rows
    List<int> mid_odd = new List<int>();
    for(int i = 0; i < N; i++)
    {
 
      // Size of current row
      int siz = Arr[i].Count;
 
      // Increase money collected by A
      for (int j = 0; j < siz / 2; j++)
        amount = amount + Arr[i][j];
 
      if(siz % 2 == 1)
        mid_odd.Add(Arr[i][siz/2]);
    }
 
    // Add coins at even indices
    // to the amount collected by A
    mid_odd.Sort();
 
    for(int i = 0; i < mid_odd.Count; i++)
      if (i % 2 == 0)
        amount = amount + mid_odd[i];
 
    // Print the amount
    Console.WriteLine(amount);
 
  }
 
  // Driver code
  static void Main()
  {
    int N = 2;
    List<List<int>> Arr = new List<List<int>>();
    Arr.Add(new List<int>());
    Arr[0].Add(5);
    Arr[0].Add(2);
    Arr[0].Add(3);
    Arr[0].Add(4);
    Arr.Add(new List<int>());
    Arr[1].Add(1);
    Arr[1].Add(6);
 
    // Function call to calculate the
    // amount of coins collected by A
    find(N, Arr);
  }
}
 
// This code is contributed by divyesh072019.


Javascript




<script>
 
// Javascript Program to implement
// the above approach
 
// Function to calculate the
// maximum amount collected by A
function find(N,  Arr)
{
     
    // Stores the money
    // obtained by A
    var amount = 0;
 
    // Stores mid elements
    // of odd sized rows
    var mid_odd = [];
    for(var i = 0; i < N; i++)
    {
 
        // Size of current row
        var siz = Arr[i].length;
 
        // Increase money collected by A
        for (var j = 0; j < siz / 2; j++)
            amount = amount + Arr[i][j];
 
        if(siz % 2 == 1)
            mid_odd.push(Arr[i][siz/2]);
    }
 
    // Add coins at even indices
    // to the amount collected by A
    mid_odd.sort((a,b)=>a-b)
 
    for(var i = 0; i < mid_odd.length; i++)
        if (i % 2 == 0)
         amount = amount + mid_odd[i];
 
    // Print the amount
    document.write( amount + "<br>");
 
}
 
// Driver Code
var N = 2;
var Arr = [[5, 2, 3, 4], [1, 6]];
 
// Function call to calculate the
// amount of coins collected by A
find(N, Arr);
 
// This code is contributed by importantly.
</script>


Output: 

8

 

Time Complexity: O(N log N), sort function takes N log N time to execute hence the overall time complexity turns out to be N log N
Auxiliary Space: O(x) where x is the number of mid elements of odd-sized rows pushed into the vector
   



Similar Reads

Maximum money that can be collected by both the players in a game of removal of coins
Given an array arr[] consisting of N positive integers, such that arr[i] represents the value of the coin, the task is to find the maximum amount of money that can be obtained by each player when two players A and B play the game optimally as per the following rules: Player A always starts the game.In each turn, a player must remove exactly 1 coin
8 min read
Maximize value of coins when coins from adjacent row and columns cannot be collected
Given a 2D array arr[][] of size N * M, the value in arr[][] represents the value of coins, the task is to maximize the value of collected coins when during collecting the coins from the arr[][], all the coins from the adjacent row (i.e, i - 1 and i + 1) will disappear, and coins at the adjacent column (i.e arr[i][j + 1] and arr[i][j - 1]) will als
9 min read
Find the maximum amount that can be collected by selling movie tickets
Given an integer N and an array seats[] where N is the number of people standing in a line to buy a movie ticket and seat[i] is the number of empty seats in the ith row of the movie theater. The task is to find the maximum amount a theater owner can make by selling movie tickets to N people. Price of a ticket is equal to the maximum number of empty
7 min read
Two player game in which a player can remove all occurrences of a number
Two players, player1 and player2, are playing a game on a given number sequence S where player1 starts first and both of them play optimally. The task is to find whether player1 wins or loses. If he wins, print "Yes", otherwise print "No". The rules of the game are as follows: The player's alternate turns.In each turn, the current player must choos
7 min read
Maximum money that can be collected among friends based on given conditions
Given an array arr[](1-based indexing) consisting of N positive integers such that arr[i] denotes the amount of the ith person. Also given are two 2D arrays say friends[][2] and groups[][2] such that each pair friends[i][0] and friends[i][1] are friends and form groups. Each pair groups[i][0] and groups[i][0] denotes the friends containing groups[i
17 min read
Maximize coins that can be collected by moving on given coordinates
Given an array arr[][] of size N*3 where ith element represents that at time arr[i][0] secs, arr[i][2] coins appear at coordinate arr[i][1]. A player starts on coordinate 0 at time 0sec and can move from one coordinate to any adjacent coordinates in 1 sec and also the player can choose to stay on the same coordinate for the next second. The task is
11 min read
Number of coins to be removed for the first player to win the Game
Two friends, A, and B are playing a game. In this game, a group of N coins is placed. The players can pick any number of coins between 1 and 4 (both inclusive) in their chance. The player who takes the last coin wins the game. If A starts first, find out how many coins should he pick such that he is guaranteed to win the game or determine if it's i
5 min read
Minimum number of coins to be collected per hour to empty N piles in at most H hours
Given an array arr[] consisting of N integers representing the number of coins in each pile, and an integer H, the task is to find the minimum number of coins that must be collected from a single pile per hour such that all the piles are emptied in less than H hours. Note: Coins can be collected only from a single pile in an hour. Examples: Input:
8 min read
Maximize the number of coins collected by X, assuming Y also plays optimally
Two players X and Y are playing a game in which there are pots of gold arranged in a line, each containing some gold coins. They get alternating turns in which the player can pick a pot from one of the ends of the line. The winner is the player who has a higher number of coins at the end. The objective is to maximize the number of coins collected b
13 min read
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other
Given two piles of coins consisting of N and M coins, the task is to check if both the piles can be emptied simultaneously by repeatedly removing 2 coins from one pile and 1 coin from the other pile. If both the piles can be made empty, then print "Yes". Otherwise, print "No". Examples: Input: N = 1, M = 2 Output: Yes Explanation: Remove 1 coin fro
6 min read