Problem solution · Java

Maximum Sum Queries

Maximum Sum Queries: a Java solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
65 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Maximum Sum Queries, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 65 lines of Java from the credited upstream file 2736.java.
  • The implementation visibly relies on sequence storage.
  • 6 loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Sum Queries · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] queries) {    MyPair[] pairs = getPairs(nums1, nums2);    IndexedQuery[] indexedQueries = getIndexedQueries(queries);    int[] ans = new int[queries.length];    List<Pair<Integer, Integer>> stack = new ArrayList<>(); // [(y, x + y)]     int pairsIndex = 0;    for (IndexedQuery indexedQuery : indexedQueries) {      final int queryIndex = indexedQuery.queryIndex;      final int minX = indexedQuery.minX;      final int minY = indexedQuery.minY;      while (pairsIndex < pairs.length && pairs[pairsIndex].x >= minX) {        MyPair pair = pairs[pairsIndex++];        // x + y is a better candidate. Given that x is decreasing, the        // condition "x + y >=  stack.get(stack.size() - 1).getValue()" suggests        // that y is relatively larger, thereby making it a better candidate.        final int x = pair.x;        final int y = pair.y;        while (!stack.isEmpty() && x + y >= stack.get(stack.size() - 1).getValue())          stack.remove(stack.size() - 1);        if (stack.isEmpty() || y > stack.get(stack.size() - 1).getKey())          stack.add(new Pair<>(y, x + y));      }      final int j = firstGreaterEqual(stack, minY);      ans[queryIndex] = j == stack.size() ? -1 : stack.get(j).getValue();    }     return ans;  }   private record MyPair(int x, int y){};  private record IndexedQuery(int queryIndex, int minX, int minY){};   private int firstGreaterEqual(List<Pair<Integer, Integer>> A, int target) {    int l = 0;    int r = A.size();    while (l < r) {      final int m = (l + r) / 2;      if (A.get(m).getKey() >= target)        r = m;      else        l = m + 1;    }    return l;  }   private MyPair[] getPairs(int[] nums1, int[] nums2) {    MyPair[] pairs = new MyPair[nums1.length];    for (int i = 0; i < nums1.length; ++i)      pairs[i] = new MyPair(nums1[i], nums2[i]);    Arrays.sort(pairs, Comparator.comparing(MyPair::x, Comparator.reverseOrder()));    return pairs;  }   private IndexedQuery[] getIndexedQueries(int[][] queries) {    IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];    for (int i = 0; i < queries.length; ++i)      indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]);    Arrays.sort(indexedQueries,                Comparator.comparing(IndexedQuery::minX, Comparator.reverseOrder()));    return indexedQueries;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗