|
1 | 1 | package g3401_3500.s3473_sum_of_k_subarrays_with_length_at_least_m |
2 | 2 |
|
3 | 3 | // #Medium #Array #Dynamic_Programming #Prefix_Sum |
4 | | -// #2025_03_06_Time_227_ms_(24.47%)_Space_99.61_MB_(48.94%) |
5 | | - |
6 | | -import kotlin.math.max |
| 4 | +// #2025_05_03_Time_33_ms_(98.18%)_Space_81.75_MB_(87.27%) |
7 | 5 |
|
8 | 6 | class Solution { |
9 | 7 | fun maxSum(nums: IntArray, k: Int, m: Int): Int { |
10 | 8 | val n = nums.size |
11 | | - // Calculate prefix sums |
12 | | - val prefixSum = IntArray(n + 1) |
13 | | - for (i in 0..<n) { |
14 | | - prefixSum[i + 1] = prefixSum[i] + nums[i] |
| 9 | + val dp = Array(k + 1) { IntArray(n + 1) { Int.MIN_VALUE } } |
| 10 | + val ps = IntArray(n + 1) |
| 11 | + for (i in nums.indices) { |
| 12 | + ps[i + 1] = ps[i] + nums[i] |
15 | 13 | } |
16 | | - // using elements from nums[0...i-1] |
17 | | - val dp = Array<IntArray>(n + 1) { IntArray(k + 1) } |
18 | | - // Initialize dp array |
19 | | - for (j in 1..k) { |
20 | | - for (i in 0..n) { |
21 | | - dp[i][j] = Int.Companion.MIN_VALUE / 2 |
22 | | - } |
| 14 | + for (j in 0..n) { |
| 15 | + dp[0][j] = 0 |
23 | 16 | } |
24 | | - // Fill dp array |
25 | | - for (j in 1..k) { |
26 | | - val maxPrev = IntArray(n + 1) |
27 | | - for (i in 0..<n + 1) { |
28 | | - maxPrev[i] = |
29 | | - if (i == 0) { |
30 | | - dp[0][j - 1] - prefixSum[0] |
31 | | - } else { |
32 | | - max(maxPrev[i - 1], dp[i][j - 1] - prefixSum[i]) |
33 | | - } |
34 | | - } |
35 | | - for (i in m..n) { |
36 | | - // Option 1: Don't include the current element in any new subarray |
37 | | - dp[i][j] = dp[i - 1][j] |
38 | | - // Option 2: Form a new subarray ending at position i |
39 | | - // Find the best starting position for the subarray |
40 | | - dp[i][j] = max(dp[i][j], prefixSum[i] + maxPrev[i - m]) |
| 17 | + for (i in 1..k) { |
| 18 | + var best = Int.MIN_VALUE |
| 19 | + for (j in (i * m)..n) { |
| 20 | + best = maxOf(best, dp[i - 1][j - m] - ps[j - m]) |
| 21 | + dp[i][j] = maxOf(dp[i][j - 1], ps[j] + best) |
41 | 22 | } |
42 | 23 | } |
43 | | - return dp[n][k] |
| 24 | + return dp[k][n] |
44 | 25 | } |
45 | 26 | } |
0 commit comments