fork download
  1. // this code is if the prob was for contiguous elem
  2. class main {
  3. public static int mingrps(int[] nums, int k) {
  4. int cnt = 0;
  5. int min = nums[0], max = nums[0];
  6. for (int i = 0; i < nums.length; i++) {
  7. max = Math.max(nums[i], max);
  8. min = Math.min(nums[i], min);
  9. if (max - min > k) {
  10. max = nums[i];
  11. min = nums[i];
  12. cnt++;
  13. }
  14. }
  15. return cnt+1; // Add 1 to account for the last group
  16. }
  17.  
  18. public static void main(String[] args) throws java.lang.Exception {
  19. int[] movies = {1, 5, 4, 6, 8, 9, 2};
  20. int k = 3;
  21. int groups = mingrps(movies, k);
  22. System.out.println("Output: " + groups);
  23. }
  24. }
  25.  
Success #stdin #stdout 0.14s 53580KB
stdin
Standard input is empty
stdout
Output: 4