- 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 maximum-total-value-of-covered-indices.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 3 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 maxTotal(vector<int>& nums, string s) {8 int64_t result = 0;9 for (int i = 0; i < size(nums);) {10 if (s[i] == '0') {11 ++i;12 continue;13 }14 result += (i - 1 >= 0) ? nums[i - 1] : 0;15 int mn = (i - 1 >= 0) ? nums[i - 1] : 0;16 int j = i;17 for (; j < size(nums) && s[j] == '1'; ++j) {18 result += nums[j];19 mn = min(mn, nums[j]);20 }21 result -= mn;22 i = j;23 }24 return result;25 }26};27 28293031class Solution2 {32public:33 long long maxTotal(vector<int>& nums, string s) {34 static const int64_t NEG_INF = numeric_limits<int64_t>::min();35 36 vector<int64_t> dp(2, NEG_INF);37 dp[0] = 0;38 for (int i = 0; i < size(nums); ++i) {39 vector<int64_t> new_dp(2, NEG_INF);40 if (s[i] == '0') {41 new_dp[0] = ranges::max(dp);42 } else {43 new_dp[1] = ranges::max(dp) + nums[i];44 if (i - 1 >= 0) {45 if (dp[0] != NEG_INF) {46 new_dp[0] = dp[0] + nums[i - 1];47 }48 }49 }50 dp = move(new_dp);51 }52 return ranges::max(dp);53 }54};55