#C9103. Maximum Subarray Sum with At Most K Distinct Elements
Maximum Subarray Sum with At Most K Distinct Elements
Maximum Subarray Sum with At Most K Distinct Elements
You are given an array of integers and an integer k. Your task is to find the maximum possible sum of any non-empty contiguous subarray that contains at most k distinct elements.
If the array is empty, output -inf
(representing negative infinity).
The subarray must be contiguous and non-empty. Formally, given an array \(A = [a_1,a_2,\dots,a_n]\) and an integer \(k\), find the maximum sum of a subarray \(A[i..j]\) such that the number of distinct elements in \(A[i..j]\) is at most \(k\).
Note: In cases where the input array is empty, the answer is defined to be \(-\infty\), which should be printed as -inf
.
inputFormat
The input is read from stdin and consists of:
- A line containing two integers
n
andk
, wheren
is the number of elements in the array andk
is the maximum number of distinct elements allowed in the subarray. - If
n > 0
, a second line containingn
integers separated by spaces representing the array elements. Ifn = 0
, there is no array element line.
You can assume that when n = 0
, k
will be 0.
outputFormat
Output a single line to stdout containing the maximum possible sum of a contiguous subarray that contains at most k
distinct elements. If the array is empty, output -inf
.
5 2
1 2 1 2 3
6