Priyanka and Toys

Sort by

recency

|

497 Discussions

|

  • + 0 comments
    int toys(vector<int> w) {
        sort(w.begin(),w.end());
        int c=0;
        size_t i = 0;
        while (i < w.size()) {
            int max = w[i] + 4;
            while (i < w.size() && w[i] <= max) {
                i++;
            }
            c++;
        }
        
        return c;
    }
    
  • + 0 comments
    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int n = input.nextInt();
            int units = 1;
            
            //Initialize the array of toys
            int[] toys = new int[n];
            for(int i = 0; i < n; i++)
                toys[i] = input.nextInt();
            
            Arrays.sort(toys); //Sort the toys ascending by weight
            
            int currentWeight = toys[0];
            for(int weight : toys)
            {
                if(!(weight <= currentWeight+4))
                {
                    units++;
                    currentWeight = weight;
                }
            }
            
            System.out.println(units);
        }
    }
    
  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/Es5l0jbSH9I

    int toys(vector<int> w) {
        sort(w.begin(), w.end());
        int result = 1, mi = w[0];
        for(int item: w){
            if(item > mi + 4){
                mi = item;
                result++;
            }
        }
        return result;
    }
    
  • + 0 comments

    python3

    def toys(w):
        # Write your code here
        
        count = 1
        w = sorted(w)
        curr = w[0]
        for i in w:
            if abs(i - curr) > 4:
                count += 1
                curr = i
        
        return count
    
  • + 0 comments

    Java:

    public static int toys(List<Integer> w) {
          Collections.sort(w);
          int n = w.size();
          int containerCount = 1;
          int minUnit = w.get(0);
          for(int i = 1; i < n; i++ ) {
            if(w.get(i) > minUnit + 4) {
              minUnit = w.get(i);
              containerCount++;
            }
          }
         return containerCount;
        }
    
    }