CHEFNWRK - Editorial

Thank you so much u made my day :yellow_heart:

1 Like

public static int findRounds(int K,int[]A) {
int rounds=0;
int temp=0;

for(int i=0;i<A.length;i++) {
	temp=temp+A[i];
	if(temp==K) {
		rounds++;
		temp=0;
		
	}
	else if(temp<K) {
		
		if((i+1)!=A.length&&(temp+A[i+1])<=K) {
	
			continue;
		}
		rounds++;
		temp=0;
		
	}
	else if(temp>K) {
		
		break;
	}
	
}
rounds=rounds==0?-1:rounds;
return rounds;

}

Full code : https://www.codechef.com/viewsolution/37115245

My solution is getting WA everytime. Although i have tested with many manual test cases,they are working fine but still problem exists when submitting. Please help me.

Language used : Java

your code is correct except last statement.

wrong–> rounds=rounds==0?-1:rounds;
correct–> rounds=(i!=A.length)?-1:rounds;

for eg- let say we are in the middle of array and at this point rounds=2 and you get out of loop by break statement. then your rounds will be something. its not necessary that it will zero. so don’t make your final answer on the basis of rounds. take i for making answer. let say (i == A.length) then we have reached to the end of array then our answer is rounds. otherwise we left in the middle of array so i will be less than A.length so our answer will be -1.
i hope you get it.

correct code----

/* 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 int findRounds(int K,int[]A) {
int rounds=0;
int temp=0;
int i;
for(i=0;i<A.length;i++) {
temp=temp+A[i];
if(temp==K) {
rounds++;
temp=0;

	}
	else if(temp<K) {
		
		if((i+1)!=A.length&&(temp+A[i+1])<=K) {
	
			continue;
		}
		rounds++;
		temp=0;
		
	}
	else if(temp>K) {
		
		break;
	}
	
}

rounds=(i!=A.length)?-1:rounds;

return rounds;

}

public static void main (String[] args) throws java.lang.Exception
{
 Scanner input=new Scanner(System.in);
	   int T=input.nextInt();
	   
	  while(T-->0){
	      int N=input.nextInt();
	      int K=input.nextInt();
	      int[] NPositions=new int[N];
	      for(int i=0;i<N;i++){
	          NPositions[i]=input.nextInt();
	      }
	      System.out.println(findRounds(K,NPositions));
	  }

}

}

1 Like

Please tell me whats wrong in my code.

for i in range(int(input())):
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    a.sort()
    i = 0
    b = 0
    c = []
    if(a[-1] >= k):
        print(-1)
    else:
        while(len(a) > 0):
            b = a[i]
            while(b < k and len(a) > 0):
                a.pop(i)
                if(len(a) > 0):
                    b += a[i]
            c.append(b)
        if(len(a) != 0):
            print(-1)
        else:
            print(len(c))

Thanks alot.

Thanks, man ! Actually, I thought I need to print possible rounds only. I didn’t know I need to print the rounds only if All boxes can be moved.

Thanks again ! :slight_smile:

2 Likes

same happened with me

1 Like

I am glad I could help😊

Please explain your logic so others can debug.

Sure sir, my approach is this. Firstly, I sort the array in ascending order and check the last element. If it is greater or equal then return -1 else go in while loop and assign value of array in variable b. Then remove that element if value of b is less then k also then check that array is not empty. Then append the value of b in array c. Lastly I check length of array c.

personally i think that your logic is wrong brother. according to me Sorting will not give you the required answer because according to question chef will take boxes in the same manner as given in array so there is no need to sort list. let take an example.
1
5 4
4 3 2 1 4
your code is giving -1.but real answer is 4 trips.
chef will take boxes in these following trips.–
first trip–[4]
second trip–[3]
third trip–[2,1]
fourth trip–[4]

Thoughts about this code in Python?

Took me quite a bit time to solve; looking to see where I could have saved some time

#*********************************************************************************

ans = []

casenum = int(input("Enter cases: "))

for _ in range(casenum):

count=0
j=0
breakflag=0

inp = input("Enter the number and total weight: ")
n = int(inp.split()[0])
k = int(inp.split()[1])

weights = input("Enter the weight array: ").split()

if (any(int(i)>k for i in weights) is True):
    ans.append(-1)
    continue

#*********************************************************************************

for i in range(n):
    
    remweight = k
    
    if (breakflag==1):
        break


    while (True):
        
        if (j>=n):
            count = count + 1
            breakflag=1
            break
        
        if(int(weights[j])<=remweight):
            remweight = remweight - int(weights[j])
            j=j+1
            continue
            
        count = count + 1
        break

#*********************************************************************************

ans.append(count)

for i in range(casenum):
print(ans[i])

Java solution : -

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {

public static void main(String[] args) {
    int T = fs.nextInt();
    for (int t = 0; t < T; t++) {
        solve();
    }
    out.close();
}

private static void solve() {
    int n = fs.nextInt();
    int k = fs.nextInt();

    int[] arr = fs.readArray(n);
    int rounds = 0;
    for(int i = 0;i<n;i++) {
        if(arr[i]>k) {
            out.println(-1);
            return;
        }
        int sum = arr[i];
        int j = i+1;
        while (j<n && sum+arr[j] <= k) {
            sum += arr[j++];
        }
        i = j-1;
        rounds++;
    }
   out.println(rounds);
}

private static final FastScanner fs = new FastScanner();
private static final PrintWriter out = new PrintWriter(System.out);

public static class FastScanner {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer("");

    String next() {
        while (!st.hasMoreTokens())
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    int[] readArray(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = nextInt();
        return a;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    String nextString() {
        return next();
    }
}

}

Thanks sir, but sorting work here for checking any element is greater then k.

for i in range(int(input())):
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    d = sorted(a)
    i = 0
    b = 0
    c = []
    if(d[-1] > k):
        print(-1)
    else:
        while(len(a) > 0):
            if(b+a[i] <= k):
                b += a[i]
                a.pop(i)
            else:
                c.append(b)
                b = 0
        if(b != 0):
            c.append(b)
            b = 0
        print(len(c))

It works here.

here also you found your answer in unsorted array. you used sorted copy of given array just for impossible case . in your previous code you were finding answer in sorted array.
use carefully

  1. a.sort()-- it will sort a
  2. b=sorted(a) – here b will be sorted but not a
    i also get confuse here many times.
    :wink:

Yup sir for possible cases I used unsorted array and used b for impossible cases. Thanks sir for your help.

1 Like

happy to help :grinning:

1 Like

You can only pick up the boxes in the order given in the input.

So sorting a won’t work. Try processing a in the original order

I’ve caught your mistake. You’ve put a conditional return statement in the input loop. If there is some Wi > k in the input, you code returns from the function and starts treating further input as another test case whereas the actual current testcase wasn’t over.

Thanks a lot.