Skip to the code
cf.
+10 XP

#464 Detect a Money-Making Loop

easy

A loyalty program lets members convert points between n partner programs numbered 0 to n - 1. Each conversions[i] = [from, to, cost] means converting from from to to costs cost points; a negative cost means the conversion gives a bonus.

If some loop of conversions has a negative total cost, members could go around it forever and earn unlimited points. Write hasMoneyLoop(n, conversions) that returns true if such a loop exists anywhere, and false otherwise.

Example 1

Input: n = 3, conversions = [[0,1,2],[1,2,-3],[2,0,0]]
Output: true

Going 0 → 1 → 2 → 0 costs 2 - 3 + 0 = -1, so each lap earns a point.

Example 2

Input: n = 3, conversions = [[0,1,2],[1,2,-1],[2,0,0]]
Output: false

The only loop costs 2 - 1 + 0 = 1, which loses a point.

Constraints

  • 1 <= n <= 200
  • 0 <= conversions.length <= 2000
  • -1000 <= cost <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).