Approach
Breadth-first search
For Mark Elements on Array by Performing Queries, 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 3080.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[] unmarkedSumArray(int[] nums, int[][] queries) {3 long[] ans = new long[queries.length];4 boolean[] marked = new boolean[nums.length];5 long sum = Arrays.stream(nums).asLongStream().sum();6 7 Queue<Pair<Integer, Integer>> minHeap =8 new PriorityQueue<>(Comparator.comparingInt(Pair<Integer, Integer>::getKey)9 .thenComparingInt(Pair<Integer, Integer>::getValue));10 11 for (int i = 0; i < nums.length; ++i)12 minHeap.offer(new Pair<>(nums[i], i));13 14 for (int queryIndex = 0; queryIndex < queries.length; ++queryIndex) {15 final int index = queries[queryIndex][0];16 final int k = queries[queryIndex][1];17 if (!marked[index]) {18 marked[index] = true;19 sum -= nums[index];20 }21 for (int popped = 0; popped < k && !minHeap.isEmpty();) {22 final int num = minHeap.peek().getKey();23 final int i = minHeap.poll().getValue();24 if (!marked[i]) {25 marked[i] = true;26 sum -= num;27 ++popped;28 }29 }30 ans[queryIndex] = sum;31 }32 33 return ans;34 }35}36