FastPrepMost Value from At Most Two Projects

Most Value from At Most Two Projects

Hudson River Trading logoHudson River Trading● MediumFULLTIMEOA

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[][]) → int

Examples

Example 1

values = [5,-2,9]requirements = [[1,2]]return = 7

Project 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 = 10

Projects 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 = 0

Projects 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^9
  • 0 <= requirements.length <= 10^4
  • requirements[i].length == 2
  • 0 <= requirements[i][0], requirements[i][1] < values.length
  • requirements[i][0] != requirements[i][1]
  • No requirement appears twice.

More Hudson River Trading problems

See Hudson River Trading hiring insights
Saved
public int maxProjectValue(int[] values, int[][] requirements) {
    // Write your code here.
}
Checking account…