A lab technician has a row of n wells on a microplate. Each well contains a sample, and from a preliminary screening she knows the amount of DNA (in ng) that can be extracted from each of them.
Unfortunately the pipetting robot is not very precise: when it extracts the sample from a well, it contaminates the two neighbouring wells, which then cannot be used anymore.
In other words, she can never extract from two adjacent wells.
Which wells should she choose to collect as much DNA as possible?
Problem Description
Given a list of integers dna, where dna[i] is the amount of DNA in well i, compute the maximum total amount of DNA that can be collected by choosing a set of wells such that no two chosen wells are adjacent.
Example
Input
[6, 7, 1, 3, 8]
Output
15
Explanation
The best choice is to extract from wells 1 and 4:
7 + 8 = 15
Note that picking wells 0, 2 and 4 gives the same total (6 + 1 + 8 = 15), while the greedy choice “always take the richest available well” is not guaranteed to work in general: try it on [5, 6, 5].
Function Description
Implement the following function:
def maxDNA(dna: list[int]) -> int:
# Write your code hereParameters
dna: list ofn ≥ 1non-negative integers,dna[i]is the amount of DNA in welli
Returns
int: maximum total amount of DNA that can be collected without using two adjacent wells
💡 Hint
Let best(i) be the maximum amount of DNA that can be collected using only the wells from 0 to i.
For well i there are only two options:
- skip it: the answer is the same as for the wells up to
i-1; - use it: then well
i-1is forbidden, and we adddna[i]to the best we can do up toi-2.
Then fill a 1D table from left to right:
| i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| dna | 6 | 7 | 1 | 3 | 8 |
| best(i) | 6 | 7 | 7 | ? | ? |
What is the time and space complexity of your solution?
Test
Input2
[5, 1, 1, 5, 10, 2, 7, 3]
Output2
23