Most Value from At Most Two Projects
Problem statement
A company has n projects, numbered 0 to n - 1. Finishing project i adds values[i] to the company's total. A value can be negative, which means that project loses money.
Each requirement [a, b] in requirements means project a must be finished before project b can start.
The company can finish at most 2 projects. A project can start only after all of its required projects are finished, so every required project must also be one of the chosen ones. Requirements can form a cycle, and a project on a cycle can never start.
Return the largest total value the company can get. Finishing no projects gives a total of 0.
Function
maxProjectValue(values: int[], requirements: int[][]) → intExamples
Example 1
values = [5,-2,9]requirements = [[1,2]]return = 7Project 2 is worth the most, but project 1 must be completed first. The sets the company can complete are:
{0}:5{1}:-2{0, 1}:5 + (-2) = 3{1, 2}:-2 + 9 = 7
Project 2 alone and {0, 2} are not allowed, because they leave out project 1. The best total is 7.
Example 2
values = [4,6,3,8]requirements = [[0,1],[1,3],[2,3]]return = 10Projects 0 and 2 have no requirements. Project 1 needs only project 0. Project 3 needs both 1 and 2, and its own chain also needs 0, so it can never fit in 2 projects.
The best choices are {0, 1} with 4 + 6 = 10, {0, 2} with 4 + 3 = 7, and single projects worth at most 4. The answer is 10.
Example 3
values = [-3,7,6]requirements = [[1,2],[2,1]]return = 0Projects 1 and 2 each require the other, so neither can ever be started. Only project 0 can be completed, and it is worth -3.
Completing nothing gives 0, which is better, so the answer is 0.
Constraints
1 <= values.length <= 10^4-10^9 <= values[i] <= 10^90 <= requirements.length <= 10^4requirements[i].length == 20 <= requirements[i][0], requirements[i][1] < values.lengthrequirements[i][0] != requirements[i][1]- No requirement appears twice.