Maximum subsequence sum such that no three are consecutive
Pattern: 1D DP
Pick values so that no three consecutive positions are all taken. At position i, either skip it, take it alone (skipping i - 1), or take it together with i - 1 (skipping i - 2).
The problem
Return the largest sum of elements such that no three consecutive elements are all chosen. [1, 2, 3] gives 5.
Think first
- What is the longest run of chosen elements allowed?
- What are the options for the last element?
- Which earlier answer does each option use?
Hints
Brute force, and why it fails
Try every subset: exponential.
The key insight
Three options at each position cover every valid ending.
Dry run
| best | 1 3 |
|---|
arr [1, 2, 3]. best(0) = 1, best(1) = 3.
Step 1 of 2
The plan
best[i] = max(best[i-1], a[i] + best[i-2], a[i] + a[i-1] + best[i-3])
Complexity
- Time
O(n)- Space
O(n)
One pass.
Edge cases
- One or two elements: take them all.
- All equal values.
- Large values.
I've built my logic, show the code
Java
class Solution {
public int findMaxSum(int[] arr) {
int n = arr.length;
int[] best = new int[n]; // best[i]: the most from arr[0..i] with no three taken in a row
for (int i = 0; i < n; i++) {
int skip = i >= 1 ? best[i - 1] : 0; // leave arr[i]
int takeOne = arr[i] + (i >= 2 ? best[i - 2] : 0); // take arr[i], skip arr[i - 1]
int takeTwo = i >= 1 ? arr[i] + arr[i - 1] + (i >= 3 ? best[i - 3] : 0) : 0; // take both, skip arr[i - 2]
best[i] = Math.max(skip, Math.max(takeOne, takeTwo));
}
return best[n - 1];
}
}C++
class Solution {
public:
int findMaxSum(vector<int>& arr) {
int n = static_cast<int>(arr.size());
vector<int> best(n, 0); // best[i]: the most from arr[0..i] with no three taken in a row
for (int i = 0; i < n; i++) {
int skip = i >= 1 ? best[i - 1] : 0; // leave arr[i]
int takeOne = arr[i] + (i >= 2 ? best[i - 2] : 0); // take arr[i], skip arr[i - 1]
int takeTwo = i >= 1 ? arr[i] + arr[i - 1] + (i >= 3 ? best[i - 3] : 0) : 0; // take both, skip arr[i - 2]
best[i] = max(skip, max(takeOne, takeTwo));
}
return best[n - 1];
}
};Python
class Solution:
def findMaxSum(self, arr: list[int]) -> int:
best = [] # best[i]: the most from arr[0..i] with no three taken in a row
for i, x in enumerate(arr):
skip = best[i - 1] if i >= 1 else 0 # leave arr[i]
take_one = x + (best[i - 2] if i >= 2 else 0) # take arr[i], skip arr[i - 1]
take_two = x + arr[i - 1] + (best[i - 3] if i >= 3 else 0) if i >= 1 else 0 # take both, skip arr[i - 2]
best.append(max(skip, take_one, take_two))
return best[-1]Common mistakes
- Allowing three in a row.
- Wrong bounds for
i < 3.