- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 55 lines of C++ from the credited upstream file minimum-cost-to-partition-a-binary-string.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 6 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long minCost(string s, int encCost, int flatCost) {8 vector<int64_t> prefix(size(s) + 1);9 const auto divide_and_conquer = [&](this auto&& divide_and_conquer, int left, int right) -> int64_t {10 const auto& l = right - left + 1;11 const auto& x = prefix[right + 1] - prefix[left];12 int64_t result = x ? l * x * encCost : flatCost;13 if (x && l % 2 == 0) {14 result = min(result, divide_and_conquer(left, (left + l / 2) - 1) + divide_and_conquer(left + l / 2, right));15 }16 return result;17 };18 19 for (int i = 0; i < size(s); ++i) {20 prefix[i + 1] = prefix[i] + (s[i] == '1' ? 1 : 0);21 }22 return divide_and_conquer(0, size(s) - 1);23 }24};25 26272829class Solution2 {30public:31 long long minCost(string s, int encCost, int flatCost) {32 int l = size(s);33 for (; l % 2 == 0; l >>= 1);34 vector<pair<int64_t, int64_t>> dp;35 for (int left = 0; left < size(s); left += l) {36 int64_t x = 0;37 for (int i = left; i < left + l; ++i) {38 x += (s[i] == '1') ? 1 : 0;39 }40 dp.emplace_back(x ? l * x * encCost : flatCost, x);41 }42 while (size(dp) != 1) {43 vector<pair<int64_t, int64_t>> new_dp;44 l <<= 1;45 for (int i = 0; i < size(dp); i += 2) {46 const auto& v = dp[i].first + dp[i + 1].first;47 const auto& x = dp[i].second + dp[i + 1].second;48 new_dp.emplace_back(x ? min(l * x * encCost, v) : flatCost, x);49 }50 dp = move(new_dp);51 }52 return dp[0].first;53 }54};55