Anubhav Mishra
3 min readAug 23, 2020

--

Chef And Work (With Solution)— August COOKOFF 2020 Codechef

Question

Chef has N small boxes arranged on a line from 1 to N. For each valid ii, the weight of the i-th box is Wi. Chef wants to bring them to his home, which is at the position 0. He can hold any number of boxes at the same time; however, the total weight of the boxes he’s holding must not exceed K at any time, and he can only pick the ith box if all the boxes between Chef’s home and the ith box have been either moved or picked up in this trip.

Therefore, Chef will pick up boxes and carry them home in one or more round trips. Find the smallest number of round trips he needs or determine that he cannot bring all boxes home.

Codechef Logo

Input

  • The first line of the input contains a single integer TT denoting the number of test cases. The description of TT test cases follows.
  • The first line of each test case contains two space-separated integers NN and KK.
  • The second line contains NN space-separated integers W1,W2,…,WNW1,W2,…,WN.

Output

For each test case, print a single line containing one integer ― the smallest number of round trips or −1−1 if it is impossible for Chef to bring all boxes home.

Constraints

  • 1≤T≤1001≤T≤100
  • 1≤N,K≤1031≤N,K≤103
  • 1≤Wi≤1031≤Wi≤103 for each valid ii

Example Input

4
1 1
2
2 4
1 1
3 6
3 4 2
3 6
3 4 3

Example Output

-1
1
2
3

Explanation

Example case 1: Since the weight of the box higher than KK, Chef can not carry that box home in any number of the round trip.

Example case 2: Since the sum of weights of both boxes is less than KK, Chef can carry them home in one round trip.

Example case 3: In the first round trip, Chef can only pick up the box at position 11. In the second round trip, he can pick up both remaining boxes at positions 22 and 33.

Example case 4: Chef can only carry one box at a time, so three round trips are required.

Solution

/* package codechef; // don't place package name! */import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int n=0,k=0;

while(t-- >0){
n = sc.nextInt();
k = sc.nextInt();
int total=0,moves=1;
int arr[] = new int [n];
for(int i=0;i<n;i++)
arr[i] = sc.nextInt();

for(int i=0;i<n;i++){
if(arr[i]>k){
moves=-1;
break;
}
else if(total+arr[i]<=k){
total= total+arr[i];
}
else{
moves++;
total = arr[i];
}
}
System.out.println(moves);

}
}
}

This solution is Just for understanding of logic after contest. In no way I urge you to cheat in the contest. Remember these challenges are only for learning.

References

--

--

Anubhav Mishra

Software Engineer , Having my degree B.Tech in Information Technology from BVCOE, New Delhi. Love new Technologies. Electronic Dance Music is love.