Problem · Graph

Shared Interest

Learn this problem
MediumInMobi logoInMobiFULLTIMEOA

Problem statement

There are friendsNodes friends numbered from 1 through friendsNodes. Each relationship connects two friends and carries an integer interest label.

Sharing an interest is transitive. For a fixed interest label, if two friends belong to the same connected component formed by relationships with that label, then they share that interest directly or indirectly.

For every unordered pair of friends, count how many distinct interest labels they share. Find the pairs with the largest such count and return the largest product of the two friend numbers among those pairs.

Function

maxShared(friendsNodes: int, friendsFrom: int[], friendsTo: int[], friendsWeight: int[]) → int

Examples

Example 1

friendsNodes = 4friendsFrom = [1,1,2,2,2]friendsTo = [2,2,3,3,4]friendsWeight = [2,3,1,3,4]return = 6

Pairs (1, 2) and (2, 3) each share two interests. Their products are 2 and 6, so the answer is 6.

Example 2

friendsNodes = 5friendsFrom = [1,2,3,1,2]friendsTo = [2,3,4,3,4]friendsWeight = [7,7,7,9,9]return = 8

Interest 7 connects friends 1 through 4. Interest 9 additionally connects pairs (1, 3) and (2, 4). Those two pairs share the maximum of two interests, and 2 * 4 = 8 is the larger product.

Example 3

friendsNodes = 6friendsFrom = [1,2,3,4,5]friendsTo = [2,3,4,5,6]friendsWeight = [1,1,1,1,1]return = 30

All six friends are connected by interest 1, so every pair ties with one shared interest. The largest product is 5 * 6 = 30.

Constraints

  • 2 <= friendsNodes <= 100
  • 1 <= friendsFrom.length <= min(200, friendsNodes * (friendsNodes - 1) / 2)
  • friendsFrom.length == friendsTo.length == friendsWeight.length
  • 1 <= friendsFrom[i], friendsTo[i] <= friendsNodes
  • friendsFrom[i] != friendsTo[i]
  • 1 <= friendsWeight[i] <= 100
  • The same pair may appear with different interest labels. Each distinct label is counted at most once for a pair.

More InMobi problems

drafts saved locally
public int maxShared(int friendsNodes, int[] friendsFrom, int[] friendsTo, int[] friendsWeight) {
    // write your code here.
}
friendsNodes4
friendsFrom[1,1,2,2,2]
friendsTo[2,2,3,3,4]
friendsWeight[2,3,1,3,4]
expected6
checking account