Approach
Breadth-first search
For Find the K-Sum of an Array, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 40 lines of Java from the credited upstream file 2386.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public long kSum(int[] nums, int k) {3 final long maxSum = getMaxSum(nums);4 final int[] absNums = getAbsNums(nums);5 long ans = maxSum;6 7 Queue<Pair<Long, Integer>> maxHeap =8 new PriorityQueue<>((a, b) -> Long.compare(b.getKey(), a.getKey()));9 maxHeap.offer(new Pair<>(maxSum - absNums[0], 0));10 11 for (int j = 0; j < k - 1; ++j) {12 Pair<Long, Integer> pair = maxHeap.poll();13 final long nextMaxSum = pair.getKey();14 final int i = pair.getValue();15 ans = nextMaxSum;16 if (i + 1 < absNums.length) {17 maxHeap.offer(new Pair<>(nextMaxSum - absNums[i + 1], i + 1));18 maxHeap.offer(new Pair<>(nextMaxSum - absNums[i + 1] + absNums[i], i + 1));19 }20 }21 22 return ans;23 }24 25 private long getMaxSum(int[] nums) {26 long maxSum = 0;27 for (final int num : nums)28 if (num > 0)29 maxSum += num;30 return maxSum;31 }32 33 private int[] getAbsNums(int[] nums) {34 for (int i = 0; i < nums.length; ++i)35 nums[i] = Math.abs(nums[i]);36 Arrays.sort(nums);37 return nums;38 }39}40