Priyanka and Toys

Sort by

recency

|

495 Discussions

|

  • + 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;
        }
    
    }
    
  • + 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

    Here is my PHP solution:

    function toys($w) {
        // Write your code here
        sort($w);
        $count_w = count($w);
        $w_first = $w[0];
        $counter = 1;
        
        for ($i=0; $i < $count_w; $i++) {
            if ($w[$i] > (4 + $w_first)) {
                $counter++;
                $w_first = $w[$i];
            }
        }  
        return $counter;
    }
    
  • + 0 comments

    code in java made by poly

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Toys {
        public static int toys(int[] w) {
            Arrays.sort(w);
            int total = 1;
            int freeToys = w[0] + 4;
            for (int i = 1; i < w.length; i++) {
                if (w[i] > freeToys) {
                    total += 1;
                    freeToys = w[i] + 4;
                }
            }
            return total;
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            int[] w = new int[n];
            for (int i = 0; i < n; i++) {
                w[i] = scanner.nextInt();
            }
            System.out.println(toys(w));
            scanner.close();
        }
    }