2461. Maximum Sum of Distinct Subarrays With Length K #851
-
Topics: You are given an integer array
Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return A subarray is a contiguous non-empty sequence of elements within an array. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can follow these steps: Approach:
Algorithm:
Let's implement this solution in PHP: 2461. Maximum Sum of Distinct Subarrays With Length K <?php
function maximumSubarraySum($nums, $k) {
$n = count($nums);
$maxSum = 0;
$currentSum = 0;
$freq = array(); // To track frequency of elements in the current window
for ($i = 0; $i < $n; $i++) {
// Add new element to the current sum and frequency map
$currentSum += $nums[$i];
$freq[$nums[$i]] = isset($freq[$nums[$i]]) ? $freq[$nums[$i]] + 1 : 1;
// If the window size exceeds k, remove the leftmost element
if ($i >= $k) {
$currentSum -= $nums[$i - $k];
$freq[$nums[$i - $k]]--;
if ($freq[$nums[$i - $k]] === 0) {
unset($freq[$nums[$i - $k]]);
}
}
// If the current window has exactly k elements and all are distinct
if ($i >= $k - 1) {
if (count($freq) === $k) {
$maxSum = max($maxSum, $currentSum);
}
}
}
return $maxSum;
}
// Example usage:
$nums1 = [1,5,4,2,9,9,9];
$k1 = 3;
echo maximumSubarraySum($nums1, $k1); // Output: 15
$nums2 = [4,4,4];
$k2 = 3;
echo maximumSubarraySum($nums2, $k2); // Output: 0
?> Explanation:
Time Complexity:
Space Complexity:
|
Beta Was this translation helpful? Give feedback.
We can follow these steps:
Approach:
k
, and we slide the window through the array while maintaining the sum of the current window and checking if all elements in the window are distinct.