Skip to content

Commit f82bdf1

Browse files
Solution Leetcode and Explaination Every single line
1 parent f8f8328 commit f82bdf1

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
✅ LeetCode 2099 – Find Subsequence of Length K With the Largest Sum
2+
3+
class Solution {
4+
public int[] maxSubsequence(int[] nums, int k) {
5+
int n = nums.length;
6+
int[][] pair = new int[n][2];
7+
8+
for (int i = 0; i < n; i++) {
9+
pair[i][0] = nums[i]; // value
10+
pair[i][1] = i; // index
11+
}
12+
13+
Arrays.sort(pair, (a, b) -> b[0] - a[0]); // sort descending by value
14+
15+
Arrays.sort(pair, 0, k, (a, b) -> a[1] - b[1]); // sort top-k by index
16+
17+
int[] res = new int[k];
18+
for (int i = 0; i < k; i++) {
19+
res[i] = pair[i][0];
20+
}
21+
22+
return res;
23+
}
24+
}
25+
26+
Explanation
27+
int[][] pair = new int[n][2];
28+
🔹 Har number ke saath uska original index bhi store kar rahe hain.
29+
pair[i][0] = value, pair[i][1] = original index
30+
31+
Arrays.sort(pair, (a, b) -> b[0] - a[0]);
32+
🔹 Array ko value ke basis par descending order me sort kar diya.
33+
Taaki sabse bade k elements mil jaayein.
34+
35+
Arrays.sort(pair, 0, k, (a, b) -> a[1] - b[1]);
36+
🔹 Top k elements mil gaye, lekin ab unhe original order me chahiye.
37+
Isliye un k elements ko index ke basis par sort kar diya.
38+
39+
int[] res = new int[k];
40+
for (int i = 0; i < k; i++) res[i] = pair[i][0];
41+
42+
🔹 Final answer banaya by extracting values from sorted top-k elements (jo ab original order me hain).
43+
44+
Example Dry Run
45+
Input:
46+
nums = [3,4,3,3], k = 2
47+
Step 1 (Pair + Sort by Value):
48+
[(4,1), (3,0), (3,2), (3,3)]
49+
50+
Step 2 (Top k = 2):
51+
[(4,1), (3,0)]
52+
53+
Step 3 (Sort by Index):
54+
[(3,0), (4,1)]
55+
56+
Output:
57+
[3, 4]
58+
59+
Time & Space Complexity
60+
Item Complexity
61+
Time O(N log N)
62+
Space O(N)
63+
64+
Need more help or Java tricks?
65+
https://www.linkedin.com/in/saurabh884095/
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.util.*;
2+
3+
public class Solution {
4+
public int[] maxSubsequence(int[] nums, int k) {
5+
int n = nums.length;
6+
int[][] pair = new int[n][2];
7+
8+
for (int i = 0; i < n; i++) {
9+
pair[i][0] = nums[i]; // value
10+
pair[i][1] = i; // index
11+
}
12+
13+
Arrays.sort(pair, (a, b) -> b[0] - a[0]); // sort descending by value
14+
15+
Arrays.sort(pair, 0, k, (a, b) -> a[1] - b[1]); // sort top-k by index
16+
17+
int[] res = new int[k];
18+
for (int i = 0; i < k; i++) {
19+
res[i] = pair[i][0];
20+
}
21+
22+
return res;
23+
}
24+
}

0 commit comments

Comments
 (0)