Maximum happiness
Limits: 2 sec., 256 MiB
This statement was translated automatically from Ukrainian.
Everyone celebrates the holiday of the 47th day of the year in their own way. Some meet with their friends and throw a loud party. Some set off loud fireworks. Some sit and solve holiday problems.
Mr. Dmytro decided to enjoy a special holiday set of candies on the occasion of the holiday. The set consists of \(n\) candies. Each candy has its own happiness level — an integer 4 or 7. All candies are arranged in a row, so that each candy except the first and the last has exactly two neighbors.
The feature of this set is that by eating a certain candy, the eater’s happiness level increases by the total happiness level of the two neighbors of the candy they eat. Note that eating the first or the last candy from the set is prohibited.
Mr. Dmytro wants to eat all the candies except the first and the last in order to achieve maximum happiness. Help him determine the maximum level of happiness he can achieve.
Input
The first line contains a single integer \(n\) — the number of candies in the set.
The second line contains \(n\) integers \(a_i\) — the happiness levels of the candies in the order they are arranged in the set.
Output
In a single line, print one integer — the maximum happiness level that can be achieved.
Constraints
7 tests: \(3 \le n \le 20\),
15 tests: \(3 \le n \le 100\),
25 tests: \(3 \le n \le 10^5\),
\(a_i \in \{4, 7\}\).
Samples
| Input (stdin) | Output (stdout) |
|---|---|
| 3 4 4 7 | 11 |
| Input (stdin) | Output (stdout) |
|---|---|
| 7 4 7 4 4 7 7 4 | 58 |
Submit a solution
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|
Maximum happiness - Editorial
The problem gives a sequence of 4s and 7s. In one operation, we can remove some element of the sequence and add the sum of its left and right neighbors to the score. We need to remove all elements except the first and the last ones, maximizing the score.
The problem is solved greedily. First we remove the 4s that neighbor at least one 7, until all 4s are removed (this can always be done if there is at least one 7). Then we remove all 7s in such an order that every 7 we remove neighbors two other 7s. The correctness of this approach is easy to see if we consider the equivalent problem with \(0\) and \(1\) instead of \(4\) and \(7\).
This algorithm can be implemented with a stack. We go over the sequence from left to right and push the elements onto the stack. If we try to put a \(7\) on a \(4\), we remove the \(4\). If we put a \(4\) on a \(7\), we remove the \(4\) (do not push it). In the end a sequence of 7s remains, which is processed separately.
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|