# HackerRank : Week of Code 30 – Candy Replenishing Robot

By | March 14, 2017

Candy Replenishing Robot : Hackerrank

Alice is hosting a party! The party lasts for t minutes, and she puts out a bowl of n candies at the beginning of the party. During each minute i , a person comes to the bowl and removes ci candies.

Alice programs the following algorithm into her robot, Bob, to replenish the candy throughout the party:

• If the party is ending (i.e., it’s time t), do not refill the bowl.
• If the bowl contains bi  candies at the end of minute i and bi<5 , add n-bi candies to the bowl.

For example n=8, if ,t=3  , and c=[5,2,4], then the candy bowl looks like this throughout the party:

Note that Bob doesn’t replenish the bowl at the party’s end, so a total of 5 candies were added during the party.

Given ,n ,t  and the number of candies removed from the bowl during each minute, print the total number of new candies Bob adds to the bowl during the party.

Input Format

The first line contains two space-separated integers describing the respective values of n and t .
The second line contains t space-separated integers describing the respective values of c0, c1, ….. ct-1.

Output Format

Print the total number of new candies Bob adds to the bowl during the party.

Sample Input 0

8 4
3 1 7 5


Sample Output 0

11


Explanation 0

The party starts out with n=8 candies in the bowl and the candies removed during each second are denoted by c=[3,1,7,5] . We break down each minute of the party like so:

1. Remove c0=3 candies, so 8-3=5 candies remain.
2. Remove c1=1 candies, so 5-1=4 candies remain. Because the party is still going on, Bob refills the bowl by adding 4   new candies so it again contains 4+4=8 candies.
3. Remove c2=7 candies, so 8-7=1 candy remains. Because the party is still going on, Bob refills the bowl by adding new candies so it again contains 1+7=8 candies.
4. Remove c3=5 candies, so 8-5=3 candies remain. Because the party is ending during this minute, Bob does not refill the bowl.

We then print the total number of candies added during the party, which is 4+7=11.

Solution

Its not difficult. You just have to maintain the counts of how much candies
you have removed and how much added likewise.

package weekOfCode30;

import java.util.Scanner;

public class CandyReplenishingRobot {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int t = scan.nextInt();
int c[] = new int[t];

for (int i = 0; i < t; i++)
c[i] = scan.nextInt();

int candiesCount = n;

for (int j = 0; j < t - 1; j++) {
candiesCount = candiesCount - c[j];
if (candiesCount < 5) {
int remCan = n - candiesCount;