Skip to content

Commit d6088b2

Browse files
Solution Leetcode and Explaination Every single line
1 parent 820cf10 commit d6088b2

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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/
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public int partitionArray(int[] nums, int k) {
3+
Arrays.sort(nums);
4+
int count = 1;
5+
int min = nums[0];
6+
7+
for (int i = 1; i < nums.length; i++) {
8+
if (nums[i] - min > k) {
9+
count++;
10+
min = nums[i];
11+
}
12+
}
13+
14+
return count;
15+
}
16+
}

0 commit comments

Comments
 (0)