Problem · Array

Min Cost to Complete All Projects

Learn this problem
EasySalesforce logoSalesforceFULLTIMEOA
See Salesforce hiring insights

Problem statement

A customer has posted several web development projects on a freelancing platform, and various web developers have put in bids for these projects. Given the bid amounts and their corresponding projects, what is the minimum amount the customer can pay to have all the projects completed?

Note: If any project has no bids, return -1.

Function

minCost(numProjects: int, projectId: int[], bid: int[]) → long

Complete the function minCost in the editor.

minCost has the following parameters:

  1. 1. int numProjects: the total number of projects posted by the client (labeled from 0 to n)
  2. 2. int projectId[n]: the projects that the freelancers bid on
  3. 3. int bid[n]: the bid amounts posted by the freelancers

Returns

long: the minimum cost the client can spend to complete all projects, or -1 if any project has no bids.

Examples

Example 1

numProjects = 3projectId = [2, 0, 1, 2]bid = [8, 7, 6, 9]return = 21

There is only one choice of who to hire for project 0, and it will cost 7. Likewise, there is only one choice for project 1, which will cost 6. For project 2, it is optimal to hire the first web developer, instead of the fourth, and doing so will cost 8. So the final answer is 7 + 6 + 8 = 21.

If instead there were n = 4 projects, the answer would be -1 since there were no bids received on the fourth project.

Example 2

numProjects = 2projectId = [0, 1, 0, 1, 1]bid = [4, 74, 47, 744, 7]return = 11

The optimal solution is to hire the first web developer to complete project 0 (which costs 4) and to hire the fifth web developer to complete project 1 (which costs 7). So the total cost for the customer will be 4 + 7 = 11.

Constraints

  • 1 ≤ numProjects, n ≤ 5x10^5
  • 0 ≤ projectId[i] < n
  • 1 ≤ bid[i] ≤ 10^9

More Salesforce problems

drafts saved locally
public long minCost(int numProjects, int[] projectId, int[] bid) {
  // write your code here
}
numProjects3
projectId[2, 0, 1, 2]
bid[8, 7, 6, 9]
expected21
checking account