Problem Description
Given two arrays, nums and cost, of equal length and an integer k, you must partition the array nums into one or more contiguous subarrays. The twist is that the cost to “pay” for each chosen subarray depends on two parts: a global prefix sum of nums up to the current subarray’s end (plus an additional k multiplied by the order/index of the subarray) and the sum of the cost values for only that subarray. Formally, if the i‑th subarray spans indices l to r, its cost is computed as (nums[0] + nums[1] + ... + nums[r] + k * i) multiplied by (cost[l] + cost[l + 1] + … + cost[r]). The task is to choose a division of the array that minimizes the total cost summed over all subarrays.
Key Insights
- The cost of any subarray [l, r] depends on a fixed “global” prefix sum of nums (from index 0 to r) combined with the order of the subarray.
- Precomputing prefix sums for both nums and cost allows quick computation of any required interval sum.
- The decision of where to split affects both the subarray’s own cost (through the cost sum) and the global prefix sum part—hinting toward a dynamic programming solution.
- A state can be defined by the ending index and the number of subarrays (or order) used, and then the solution is recovered by taking the minimum over all allowable partitions.
- Although a straightforward DP approach may lead to cubic time complexity (O(n^3)), techniques such as convex hull trick or other optimizations can reduce it given the “linearity” hidden in parts of the recurrence.
Space and Time Complexity
Time Complexity: O(n^2) with optimization (the naïve solution is O(n^3) but can be optimized using techniques such as convex hull optimization) Space Complexity: O(n^2)
Solution
We solve the problem by defining a DP state dp[m][r] where m represents the number of subarrays formed and r is the ending index of the array used. For a subarray spanning indices l to r that is the m‑th subarray, its cost is computed as: cost(l, r, m) = (prefix_nums[r] + k * m) * (prefix_cost[r] – (l > 0 ? prefix_cost[l-1] : 0)) For m = 1 (only one subarray), we have: dp[1][r] = (prefix_nums[r] + k) * prefix_cost[r] For m > 1, we try every possible split position l (where the m‑th subarray starts at l and ends at r) and update: dp[m][r] = min for all l in [m-1, r] { dp[m-1][l-1] + cost(l, r, m) } Finally, the answer is the minimum dp[m][n-1] over all m between 1 and n. The trick here is to use the precomputed prefix sums (prefix_nums and prefix_cost) so that the cost for any subarray [l, r] is computed in constant time. This DP formulation naturally highlights the trade off between making many cuts (increasing m and thus the additional k * m factor) and fewer cuts (resulting in cost sums that might be larger).