Codey and Coins
https://www.hackerrank.com/contests/codenection-2024-preliminary-round-closed-category/challenges/cn24-3
Question
Codey is hanging around a bustling market when it spots n
money bags scattered along a straight path. This market can be visualized as a one-dimensional axis, with Codey starting at position . Codey wants to gather these coins without drawing too much attention, so it follows a specific pattern to avoid being noticed.
Each money bag i
is located at position at and contains coins. At the start, Codey can choose to walk either to the right or to the left. Each time Codey collects the coins from the money bag at a specific position, it must reverse its direction and continue its search for money bags in the opposite direction.
Codey will keep switching directions and collect coins until there are no more money bags available in the direction it is facing that it hasn’t already collected.
What is the maximum number of coins Codey can gather?
Input Format
The first line contains an integer, n
, where n
represents the number of money bags in the market.
The following n
lines contains two integers, and , where represents the position of the i
-th money bag and represents the number of coins in it.
Constraints
It's guaranteed that there's at most one money bag at each x-coordinate.
There are no money bag at x = 0.
Output Format
Output the maximum number of coins Codey can collect.
Sample Inputs:
Input
Output
Explanation
There are 4 money bags, each positioned at -2, -1, 1 and 4. Codey starts at 0 and collects coins by moving as follows:
Moves right to 1,
Reverses direction and moves left to -1,
Reverses direction and moves right to 4,
Reverses direction and moves left to -2.
Hence, the maximum number of coin collected is .
Last updated