LeetCode 2386: Find the K-Sum of an Array

Problem Description

Explanation

To find the K-Sum of an array, we will use a binary search approach on the range of possible subsequence sums. We will sort the input array and then use binary search to find the kth largest subsequence sum within a range of possible sums.

  1. Sort the input array in non-decreasing order.
  2. Perform a binary search on the range of possible subsequence sums.
  3. In each iteration of the binary search:
    • Calculate a mid value within the range.
    • Check if it is possible to obtain k subsequence sums that are greater than or equal to the mid value.
    • Adjust the search range accordingly.
  4. Return the final result after the binary search.

Time complexity: O(n log(max-min)) where n is the number of elements in the input array and max-min is the range of possible subsequence sums. Space complexity: O(1)

Solutions

class Solution {
    public int kthLargestValue(int[] nums, int k) {
        Arrays.sort(nums);
        
        int left = nums[0], right = nums[nums.length - 1];
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (countSubsequenceSums(nums, mid) >= k) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        
        return left - 1;
    }
    
    private int countSubsequenceSums(int[] nums, int target) {
        int count = 0;
        int sum = 0;
        
        for (int num : nums) {
            sum += num;
            if (sum >= target) {
                count++;
                sum = 0;
            }
        }
        
        return count;
    }
}

Loading editor...