LeetCode: Network Delay Time Bellman Ford C#
You can optimize a bit by make it possible to step out of the first outer loop if the inner foreach-loop doesn't make any changes to dist in one iteration.



Wouldn't it be possible to test for maxWait whenever you update dist[v] in the foreach-loop:

{
    dist[v] = dist[u] + w;
    maxWait = Math.Max(maxWait, dist[v]);
}


This may og may not be an optimization - depending on the cost of comparing two integers potentially N * N times compared to the cost of an extra loop comparing them N-1 times?



You could make an early return in the find-max-loop:

       int maxWait = 0;
        for (int i = 1; i &lt;= N; i++)
        {
          maxWait = Math.Max(maxWait, dist[i]);

          if (maxWait == int.MaxValue)
          {
            return -1;
          }
        }


or change it to:

int maxWait = dist.Skip(1).Max();
return maxWait &lt; int.MaxValue ? maxWait : -1;