|
| 1 | +✅ Java Code (Clean, Fast, Accurate Parsing) |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public int partitionArray(int[] nums, int k) { |
| 5 | + Arrays.sort(nums); |
| 6 | + int count = 1; |
| 7 | + int min = nums[0]; |
| 8 | + |
| 9 | + for (int i = 1; i < nums.length; i++) { |
| 10 | + if (nums[i] - min > k) { |
| 11 | + count++; |
| 12 | + min = nums[i]; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + return count; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +📘 Explanation |
| 22 | + |
| 23 | +Arrays.sort(nums); |
| 24 | +🔹 Sabse pehle array ko sort kar diya — taaki hum increasing order mein process kar sakein. |
| 25 | + |
| 26 | +int count = 1; |
| 27 | +🔹 Kam se kam ek group toh hoga hi — isliye count = 1 se start kiya. |
| 28 | + |
| 29 | +int min = nums[0]; |
| 30 | +🔹 Pehle group ka starting point ya minimum value nums[0] set kiya. |
| 31 | + |
| 32 | +for (int i = 1; i < nums.length; i++) { |
| 33 | +🔹 Index 1 se lekar end tak array ko traverse kiya. |
| 34 | + |
| 35 | +if (nums[i] - min > k) { |
| 36 | +🔹 Agar current element aur group ka minimum ka difference k se zyada ho gaya... |
| 37 | + |
| 38 | +count++; |
| 39 | +🔹 ...toh naya group banayenge → isliye count ko badha diya. |
| 40 | + |
| 41 | +min = nums[i]; |
| 42 | +🔹 Naye group ka starting point ab current number ban gaya. |
| 43 | + |
| 44 | +return count; |
| 45 | +🔹 Total number of groups return kar diya. |
| 46 | + |
| 47 | +🧠 Example |
| 48 | +Input: nums = [3,6,1,2,5], k = 2 |
| 49 | +Sorted: [1,2,3,5,6] |
| 50 | +Output: 2 |
| 51 | +Groups: [1,2,3], [5,6] — because in each group, max - min ≤ 2. |
| 52 | + |
| 53 | +🚀 Time and Space Complexity |
| 54 | +Time: O(n log n) → for sorting |
| 55 | +Space: O(1) → no extra space |
| 56 | + |
| 57 | +🔗 Facing any issue or want more Java tricks? |
| 58 | +Connect here: https://www.linkedin.com/in/saurabh884095/ |
0 commit comments