702765. Mr. Modulo and Arrays

Medium

Mr. Modulo and Arrays

Summary

Mr. Modulo is a clever fellow who loves arrays. He has an array of N integers, where each element is between 1 and K (inclusive). His task is to find the maximum sum of any subarray within the given range [L, R] such that all elements in the subarray are congruent modulo M.

This problem requires a combination of array manipulation, binary search, and mathematical concepts. It's an interesting challenge that tests your understanding of arrays, modular arithmetic, and algorithmic thinking.

Detailed Explanation

To solve this problem, we'll need to first understand the concept of congruence modulo M. For two integers x and y, x is congruent to y modulo M if their remainder when divided by M is the same. In other words, x % M == y % M.

We can use binary search to find the maximum sum of any subarray within the range [L, R] that satisfies the given condition. Here's a step-by-step breakdown of the solution:

  1. Initialize a variable max_sum to store the maximum sum found so far.
  2. Perform a binary search on the array to find the smallest element in the range [L, R] that is congruent modulo M with the first element of the array.
  3. Calculate the sum of all elements in the subarray from the found element to the end of the range [R].
  4. Update max_sum if the calculated sum is greater than the current maximum sum.
  5. Repeat steps 2-4 until the binary search space is exhausted.
  6. Return the maximum sum found (max_sum) as the result.

Here's a diagram illustrating the problem:

  +---------------+
  | L (inclusive) |
  +---------------+
  | ...           |
  +---------------+
  | R (exclusive) |
  +---------------+

  Find the maximum sum of any subarray within [L, R]
  such that all elements are congruent modulo M.

Time complexity: O(N log K) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int maxSum(int[] arr, int L, int R, int M) {
    int max_sum = 0;
    for (int i = L; i <= R; i++) {
        int remain = i % M;
        int sum = 0;
        for (int j = i; j < R && arr[j] % M == remain; j++) {
            sum += arr[j];
        }
        max_sum = Math.max(max_sum, sum);
    }
    return max_sum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.