▲ 1 r/LeetcodeDesi
I came up with this solution but i am getting TLE on 622th testcase. How to fix and write the most optimal approach and how that thought process comes to you
class Solution {
public long[] findMaxSum(int[] nums1, int[] nums2, int k) {
int n = nums1.length;
long[] ans = new long[n];
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> Integer.compare(b[1],a[1]));
for(int i = 0; i < n; i++) {
int[] temp = {nums1[i],nums2[i]};
pq.offer(temp);
}
for(int i = 0; i < n; i++) {
ArrayList<int[]> temp = new ArrayList<>();
int curr = k;
long res = 0;
while(curr > 0 && !pq.isEmpty()) {
int[] arr = pq.poll();
if(nums1[i] > arr[0]) {
res += arr[1];
curr--;
}
temp.add(arr);
}
ans[i] = res;
for(int[] arr : temp) {
pq.offer(arr);
}
}
return ans;
}
}
u/Kritiraj108_ — 14 days ago