Leetcode 2386 Find the K-Sum of an Array Solution in Java | Hindi Coding Community

0

 



You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together.

We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct).

Return the K-Sum of the array.

subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Note that the empty subsequence is considered to have a sum of 0.

 

Example 1:

Input: nums = [2,4,-2], k = 5
Output: 2
Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:
- 6, 4, 4, 2, 2, 0, 0, -2.
The 5-Sum of the array is 2.

Example 2:

Input: nums = [1,-2,3,4,-10,12], k = 16
Output: 10
Explanation: The 16-Sum of the array is 10.

 

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • -109 <= nums[i] <= 109
  • 1 <= k <= min(2000, 2n)
Java Code :



class Solution {
public long kSum(int[] nums, int k) {
long minus = 0, all = 0;
for (int i = 0; i < nums.length; i++){
all += Math.max(nums[i], 0);
nums[i] = Math.abs(nums[i]);
}
Arrays.sort(nums);
var minheap = new PriorityQueue<long[]>(Comparator.comparingLong(o -> o[0]));
minheap.offer(new long[]{nums[0], 0});
while(--k>0){
long[] top = minheap.poll();
int i = (int)top[1]++;
long val = top[0];
minus = val;
if (i < nums.length-1){
top[0] += nums[i+1];
minheap.offer(new long[]{val - nums[i] + nums[i+1], i+1});
minheap.offer(top);
}
}
return all - minus;
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !