#K55097. Maximum Golden Fruits Collection
Maximum Golden Fruits Collection
Maximum Golden Fruits Collection
You are given an orchard with n trees aligned from west to east. Each tree produces a certain number of golden fruits, given by an array fruits
. However, some trees are untraversable, as indicated by a corresponding array untraversable
where a value of 1 (or true) means the tree cannot be visited and a value of 0 (or false) means it is accessible.
Starting from the westernmost tree, you must move eastward. If the first tree is untraversable, no fruits can be collected. Otherwise, if a tree is accessible, you collect its fruits. However, if the immediate previous tree is untraversable, you must add the fruits from the most recent accessible tree before that (if any). Formally, define a dynamic programming state dp[i]
as the maximum number of fruits collected up to tree i. The recurrence is given by:
\(dp[0] = \begin{cases} fruits[0], & \text{if } untraversable[0]=0 \\ 0, & \text{if } untraversable[0]=1 \end{cases}\)
For \(i \ge 1\):
\(dp[i] = \begin{cases} \ dp[i-1] + fruits[i] & \text{if } untraversable[i] = 0 \text{ and } untraversable[i-1] = 0,\\ \ ( (i \ge 2 ? dp[i-2] : 0) + fruits[i] ) & \text{if } untraversable[i] = 0 \text{ and } untraversable[i-1] = 1,\\ \ 0 & \text{if } untraversable[i] = 1. \end{cases}\)
The answer is the maximum value in the dp
array. Your task is to implement a program that computes the maximum number of golden fruits collection following the above rules.
inputFormat
The input is read from stdin and has the following format:
- An integer
n
representing the number of trees. - A line with
n
space-separated integers representingfruits
, where the i-th integer is the number of golden fruits on the i-th tree. - A line with
n
space-separated integers (either 0 or 1) representinguntraversable
, where 1 indicates the tree is untraversable and 0 indicates it is accessible.
outputFormat
Output a single integer to stdout which is the maximum number of golden fruits that can be collected.
## sample5
2 3 1 5 4
0 0 1 0 0
14