891371. Max Sum Subarray Mod
Medium
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:
- Initialize an array
dpwith size equal to the length of the input array. - For each element
arr[i]in the array, calculate its prefix sumprefixSumby iterating from0toi-1and adding the elements at those indices toprefixSum. - Calculate the maximum sum of a subarray ending at index
ias the maximum of the current elementarr[i]and the maximum sum of a subarray ending at the previous index(i-1)plus the current elementarr[i]. This is because we can either include the current element in our subarray or not. - Update
dp[i]with the calculated maximum sum modulom. - Finally, return the maximum value in the
dparray modulom.
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;
}