LeetCode 1191: K-Concatenation Maximum Sum Solution
Master LeetCode problem 1191 (K-Concatenation Maximum Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1191. K-Concatenation Maximum Sum
Problem Explanation
Explanation
To solve this problem, we can use Kadane's algorithm to find the maximum subarray sum. We need to consider two cases:
- The maximum subarray sum within a single array
arr. - The maximum subarray sum that can include elements from multiple concatenated arrays.
We can calculate the maximum subarray sum within a single array using Kadane's algorithm. Then, we can calculate the sum of all elements in the array and find the maximum subarray sum that includes elements from multiple arrays. This sum can be calculated by considering the prefix sum and suffix sum of the array concatenated k times.
Solution Code
class Solution {
public int kConcatenationMaxSum(int[] arr, int k) {
int mod = 1000000007;
int maxSingle = kadane(arr);
if (k == 1) {
return maxSingle;
}
int totalSum = 0;
for (int num : arr) {
totalSum = (totalSum + num) % mod;
}
int prefixSum = 0, maxPrefixSum = 0, suffixSum = 0, maxSuffixSum = 0;
for (int i = 0; i < arr.length; i++) {
prefixSum = (prefixSum + arr[i]) % mod;
maxPrefixSum = Math.max(maxPrefixSum, prefixSum);
}
for (int i = arr.length - 1; i >= 0; i--) {
suffixSum = (suffixSum + arr[i]) % mod;
maxSuffixSum = Math.max(maxSuffixSum, suffixSum);
}
int maxMiddleSum = Math.max(0, totalSum * (k - 2) + maxPrefixSum + maxSuffixSum) % mod;
return Math.max(maxSingle, maxMiddleSum);
}
private int kadane(int[] arr) {
int maxSum = 0;
int currentSum = 0;
for (int num : arr) {
currentSum = Math.max(num, currentSum + num);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum < 0 ? 0 : maxSum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1191 (K-Concatenation Maximum Sum)?
This page provides optimized solutions for LeetCode problem 1191 (K-Concatenation Maximum Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1191 (K-Concatenation Maximum Sum)?
The time complexity for LeetCode 1191 (K-Concatenation Maximum Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1191 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1191 in Java, C++, or Python.