LeetCode 2372: Calculate the Influence of Each Salesperson

Database

Problem Description

Explanation:

To calculate the influence of each salesperson, we can model the relationships between salespeople as a directed graph where each edge represents influence from one salesperson to another. We can then perform a topological sort on this graph to determine the influence of each salesperson.

Algorithm:

  1. Create a directed graph where each vertex represents a salesperson and each edge represents influence from one salesperson to another.
  2. Perform a topological sort on the graph to determine the order in which salespeople influence each other.
  3. For each salesperson in the sorted order, calculate their influence by summing the influences of the salespeople who influence them.
  4. Return the influence of each salesperson.

Time Complexity:

  • Building the graph: O(N), where N is the number of relationships between salespeople.
  • Topological sort: O(V + E), where V is the number of vertices (salespeople) and E is the number of edges (relationships).
  • Calculating influence: O(V), where V is the number of vertices. Overall time complexity: O(N + V + E)

Space Complexity:

  • Graph: O(V + E)
  • Influence array: O(V) Overall space complexity: O(V + E)

: :

Solutions

import java.util.*;

class Solution {
    public int[] calculateInfluence(int n, int[][] sales) {
        List<Integer>[] graph = new List[n];
        int[] influence = new int[n];

        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }

        for (int[] sale : sales) {
            graph[sale[0]].add(sale[1]);
        }

        for (int i = 0; i < n; i++) {
            for (int j : graph[i]) {
                influence[j] += 1 + influence[i];
            }
        }

        return influence;
    }
}

Loading editor...