Skip to the code
cf.
+10 XP

#2 Pick the Cheapest Plan

easy

Your team is choosing how to process a list of n records. Each plan in plans names its growth rate, and the exact number of steps it takes is:

  • "1": 1 step
  • "log n": Math.log2(n) steps
  • "n": n steps
  • "n log n": n * Math.log2(n) steps
  • "n^2": n * n steps
  • "2^n": 2 ** n steps

Write cheapestPlan(n, plans) that returns the index of the plan with the fewest steps for this n. If several plans tie, return the smallest index. Notice that for small n, the plan with the better growth rate doesn't always win.

Example 1

Input: n = 16, plans = ["n^2","n log n","2^n"]
Output: 1

The plans take 256, 64, and 65,536 steps, so index 1 is cheapest.

Example 2

Input: n = 4, plans = ["2^n","n^2"]
Output: 0

Both take 16 steps. On a tie, return the smaller index.

Constraints

  • 1 <= n <= 50
  • 1 <= plans.length <= 10
  • Each plan is one of the six names above.
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).