Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

891371. Max Sum Subarray Mod

Max Sum Subarray Mod

Slug: max-sum-subarray-mod

Difficulty: Medium

Id: 891371

Topic Tags: prefix-sum, Mathematical, Data Structures, Algorithms

Company Tags: None

Summary

Given an array of integers, find the maximum sum of a subarray that can be obtained by taking any subset of the given array and then applying modulo operation on it. The modulo operation is applied element-wise.

The key concepts involved are prefix sums, mathematical manipulation, data structures, and algorithms.

Detailed Explanation

To solve this problem, we will use dynamic programming with prefix sums. We will maintain an array dp where dp[i] represents the maximum sum of a subarray ending at index i. The final answer is the maximum value in the dp array modulo m.

Here's a step-by-step breakdown of the solution:

  1. Initialize an array dp with size equal to the length of the input array.
  2. For each element arr[i] in the array, calculate its prefix sum prefixSum by iterating from 0 to i-1 and adding the elements at those indices to prefixSum.
  3. Calculate the maximum sum of a subarray ending at index i as the maximum of the current element arr[i] and the maximum sum of a subarray ending at the previous index (i-1) plus the current element arr[i]. This is because we can either include the current element in our subarray or not.
  4. Update dp[i] with the calculated maximum sum modulo m.
  5. Finally, return the maximum value in the dp array modulo m.

Time complexity: O(n) Space complexity: O(1)

Optimized Solutions

Java

public int maxSumSubarrayMod(int[] arr, int m) {
    int n = arr.length;
    int[] dp = new int[n];
    int maxSum = 0;

    for (int i = 0; i < n; i++) {
        if (i == 0) {
            dp[i] = arr[i];
        } else {
            dp[i] = Math.max(arr[i], dp[i-1] + arr[i]) % m;
        }
        maxSum = Math.max(maxSum, dp[i]);
    }

    return maxSum;
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.