To solve the problem of finding the number of ways to choose k non-overlapping subarrays from an array of n elements where each subarray has at least m elements, we can use dynamic programming with space optimization.
Approach
-
Dynamic Programming (DP) Setup:
- Let
dp[i][j]denote the number of ways to choose j non-overlapping subarrays from the first i elements. - We use
sum_dp[i][j]to store the prefix sum ofdp[0..i][j]to optimize the calculation of subarray endings.
- Let
-
Key Observations:
- Case 1: The i-th element is not part of any subarray. So
dp[i][j] += dp[i-1][j]. - Case 2: The i-th element is the end of a subarray. This subarray must start at a position
swheres <= i - m + 1(since the subarray length is at least m). The number of ways here is the sum ofdp[0..i-m][j-1], which issum_dp[i-m][j-1].
- Case 1: The i-th element is not part of any subarray. So
-
Space Optimization:
- Instead of using 2D arrays for
dpandsum_dp, we use 1D arrays to reduce space complexity from O(nk) to O(n).
- Instead of using 2D arrays for
Solution Code
MOD = 10**9 + 7
def count_ways(n, k, m):
if k * m > n:
return 0
# prev_sum holds sum_dp[i][j-1] for all i
prev_sum = [0] * (n + 1)
for i in range(n + 1):
prev_sum[i] = (i + 1) % MOD # sum_dp[i][0] = i+1 (since dp[x][0] =1 for all x)
curr_dp = [0] * (n + 1)
for j in range(1, k + 1):
curr_dp[0] = 0 # dp[0][j] =0 for j>0
curr_sum = [0] * (n + 1)
curr_sum[0] = 0
for i in range(1, n + 1):
# Case1: i-th element not used
curr_dp[i] = curr_dp[i-1]
# Case2: i-th element is end of a subarray (length >=m)
if i >= m:
curr_dp[i] += prev_sum[i - m]
curr_dp[i] %= MOD
# Update current sum for next j
curr_sum[i] = (curr_sum[i-1] + curr_dp[i]) % MOD
# Prepare for next iteration: prev_sum becomes curr_sum (sum_dp[i][j])
prev_sum = curr_sum
return curr_dp[n] % MOD
Explanation
- Initialization:
prev_sumis initialized to handle the base case where j=0 (choosing no subarrays). - Iterate Over Subarrays: For each j (number of subarrays), compute the number of ways using the previous sum array to get the sum of valid subarray starts.
- Space Optimization: By using 1D arrays, we efficiently compute the result without storing all previous layers of DP values.
This approach ensures that we handle all edge cases (like when k*m >n) and compute the result in O(nk) time with O(n) space, which is optimal for most practical scenarios. The result is returned modulo 10^9+7 to handle large numbers.
Example: For n=5, k=2, m=2, the result is 5, which corresponds to the valid pairs of subarrays: [1-2 & 3-4], [1-2 &3-5], [1-2 &4-5], [1-3 &4-5], [2-3 &4-5]. This confirms the correctness of the solution.
Edge Cases:
- If k=0: Return 1 (only one way to choose no subarrays).
- If n <k*m: Return 0 (not enough elements to form k subarrays of length m each).
This solution is efficient and handles all possible cases correctly. It is suitable for programming contest problems where space and time constraints are important.


作者声明:本文包含人工智能生成内容。