|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.TreeMap; |
| 4 | + |
| 5 | +/** |
| 6 | + * 1296. Divide Array in Sets of K Consecutive Numbers |
| 7 | + * |
| 8 | + * Given an array of integers nums and a positive integer k, |
| 9 | + * find whether it's possible to divide this array into sets of k consecutive numbers |
| 10 | + * Return True if its possible otherwise return False. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * Input: nums = [1,2,3,3,4,4,5,6], k = 4 |
| 14 | + * Output: true |
| 15 | + * Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]. |
| 16 | + * |
| 17 | + * Example 2: |
| 18 | + * Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3 |
| 19 | + * Output: true |
| 20 | + * Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]. |
| 21 | + * |
| 22 | + * Example 3: |
| 23 | + * Input: nums = [3,3,2,2,1,1], k = 3 |
| 24 | + * Output: true |
| 25 | + * |
| 26 | + * Example 4: |
| 27 | + * Input: nums = [1,2,3,4], k = 3 |
| 28 | + * Output: false |
| 29 | + * Explanation: Each array should be divided in subarrays of size 3. |
| 30 | + * |
| 31 | + * Constraints: |
| 32 | + * 1 <= nums.length <= 10^5 |
| 33 | + * 1 <= nums[i] <= 10^9 |
| 34 | + * 1 <= k <= nums.length |
| 35 | + * */ |
| 36 | +public class _1296 { |
| 37 | + public static class Solution1 { |
| 38 | + public boolean isPossibleDivide(int[] nums, int k) { |
| 39 | + if (nums.length % k != 0) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + TreeMap<Integer, Integer> treeMap = new TreeMap(); |
| 43 | + int min = nums[0]; |
| 44 | + for (int num : nums) { |
| 45 | + treeMap.put(num, treeMap.getOrDefault(num, 0) + 1); |
| 46 | + min = Math.min(min, num); |
| 47 | + } |
| 48 | + while (!treeMap.isEmpty()) { |
| 49 | + if (!isConsecutiveK(treeMap, min, k)) { |
| 50 | + return false; |
| 51 | + } |
| 52 | + min = findNextMin(treeMap); |
| 53 | + if (min == Integer.MIN_VALUE) { |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + return true; |
| 58 | + } |
| 59 | + |
| 60 | + private int findNextMin(TreeMap<Integer, Integer> treeMap) { |
| 61 | + return treeMap.isEmpty() ? Integer.MIN_VALUE : treeMap.entrySet().iterator().next().getKey(); |
| 62 | + } |
| 63 | + |
| 64 | + private boolean isConsecutiveK(TreeMap<Integer, Integer> treeMap, int min, int k) { |
| 65 | + int count = treeMap.get(min); |
| 66 | + treeMap.remove(min); |
| 67 | + for (int i = 1; i < k; i++) { |
| 68 | + int key = min + i; |
| 69 | + if (!treeMap.containsKey(key) || treeMap.get(key) < count) { |
| 70 | + return false; |
| 71 | + } else if (treeMap.get(key) > count) { |
| 72 | + treeMap.put(key, treeMap.get(key) - count); |
| 73 | + } else { |
| 74 | + treeMap.remove(key); |
| 75 | + } |
| 76 | + } |
| 77 | + return true; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments