Approach
Breadth-first search
For Choose K Elements With Maximum Sum, 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
- 36 lines of Java from the credited upstream file 3478.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 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.
1 2class Solution {3 public long[] findMaxSum(int[] nums1, int[] nums2, int k) {4 final int n = nums1.length;5 long[] ans = new long[n];6 Pair<Integer, Integer>[] numAndIndexes = new Pair[n];7 Queue<Long> minHeap = new PriorityQueue<>();8 9 for (int i = 0; i < n; ++i)10 numAndIndexes[i] = new Pair<>(nums1[i], i);11 12 Arrays.sort(numAndIndexes, Comparator.comparingInt(Pair::getKey));13 14 final int firstIndex = numAndIndexes[0].getValue();15 minHeap.offer((long) nums2[firstIndex]);16 long sum = nums2[firstIndex];17 18 for (int i = 1; i < n; ++i) {19 final int currNum = numAndIndexes[i].getKey();20 final int currIndex = numAndIndexes[i].getValue();21 final int prevNum = numAndIndexes[i - 1].getKey();22 final int prevIndex = numAndIndexes[i - 1].getValue();23 if (currNum == prevNum)24 ans[currIndex] = ans[prevIndex];25 else26 ans[currIndex] = sum;27 minHeap.offer((long) nums2[currIndex]);28 sum += nums2[currIndex];29 if (minHeap.size() == k + 1)30 sum -= minHeap.poll();31 }32 33 return ans;34 }35}36