FastPrepTotals from a Tiered Rate Table

Totals from a Tiered Rate Table

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW

Problem statement

A tiered rate table charges different parts of an amount at different rates, like tax brackets or sales commission tiers.

The table has n tiers. Tier i starts at starts[i] and has a rate of rates[i] percent. The first tier starts at 0, and the starting points strictly increase. Tier i covers the part of an amount above starts[i] and up to starts[i + 1]. The last tier has no upper limit.

For an amount x, each tier charges its rate on the part of x that falls inside it, and the total for x is the sum of those charges. Amounts and starting points are whole units, such as dollars. Return each total in hundredths of a unit, such as cents, so every total is a whole number: a part of size p in a tier with rate r adds exactly p * r.

You are given many amounts in amounts. Return an array answer where answer[j] is the total for amounts[j].

Function

tieredTotals(starts: int[], rates: int[], amounts: int[]) → long[]

Examples

Example 1

starts = [0,10000,40000]rates = [0,10,20]amounts = [5000,25000,60000]return = [0,150000,700000]

The tiers are 0 to 10000 at 0%, 10000 to 40000 at 10%, and above 40000 at 20%.

  • 5000 lies entirely in the first tier, so its total is 0.
  • 25000 has 15000 in the second tier, so its total is 15000 * 10 = 150000 cents.
  • 60000 has 30000 in the second tier and 20000 in the third tier, so its total is 30000 * 10 + 20000 * 20 = 700000 cents.

Example 2

starts = [0]rates = [7]amounts = [0,1,100]return = [0,7,700]

There is one tier with no upper limit, so every unit of an amount is charged 7%. The totals are 0 * 7 = 0, 1 * 7 = 7, and 100 * 7 = 700 cents.

Example 3

starts = [0,100,500]rates = [5,3,1]amounts = [100,500,501]return = [500,1700,1701]

Rates do not have to increase. Here they go down, like a commission plan that pays less on later sales.

  • 100 fills the first tier exactly: 100 * 5 = 500.
  • 500 fills the first two tiers exactly: 100 * 5 + 400 * 3 = 1700.
  • 501 adds one unit in the last tier: 1700 + 1 * 1 = 1701.

Constraints

  • 1 <= starts.length <= 10^5
  • rates.length == starts.length
  • starts[0] == 0 and starts[i] < starts[i + 1]
  • 0 <= starts[i] <= 10^9
  • 0 <= rates[i] <= 100
  • 1 <= amounts.length <= 10^5
  • 0 <= amounts[j] <= 10^9

More Microsoft problems

See Microsoft hiring insights
Saved
public long[] tieredTotals(int[] starts, int[] rates, int[] amounts) {
    // Write your solution here.
}
Checking account…