You are given a 0-indexed 2D integer array brackets
where brackets[i] = [upper<sub>i</sub>, percent<sub>i</sub>]
means that the i<sup>th</sup>
tax bracket has an upper bound of upper<sub>i</sub>
and is taxed at a rate of percent<sub>i</sub>
. The brackets are sorted by upper bound (i.e. upper<sub>i-1</sub> < upper<sub>i</sub>
for 0 < i < brackets.length
).
Tax is calculated as follows:
upper<sub>0</sub>
dollars earned are taxed at a rate of percent<sub>0</sub>
.upper<sub>1</sub> - upper<sub>0</sub>
dollars earned are taxed at a rate of percent<sub>1</sub>
.upper<sub>2</sub> - upper<sub>1</sub>
dollars earned are taxed at a rate of percent<sub>2</sub>
.You are given an integer income
representing the amount of money you earned. Return the amount of money that you have to pay in taxes.
Example:
brackets = [[3,50],[7,10],[12,25]], income = 10
Based on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket. The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively. In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.
Write a function to calculate the taxes owed, given the tax brackets and income.
## Optimal Solution
This problem can be solved by iterating through the `brackets` array and calculating the tax for each bracket based on the income. We maintain a running tax total and adjust the income as we move through the brackets.
```python
def calculateTax(brackets, income):
tax = 0.0
prev_upper = 0
for upper, percent in brackets:
taxable_income = min(income, upper - prev_upper)
if taxable_income > 0:
tax += taxable_income * (percent / 100.0)
income -= taxable_income
if income == 0:
break
prev_upper = upper
return tax
Example:
brackets = [[3,50],[7,10],[12,25]]
income = 10
print(calculateTax(brackets, income))
The algorithm iterates through the brackets
array at most once. The number of brackets is limited by the constraints to a maximum of 100. Therefore, the run-time complexity is O(n), where n is the number of brackets. In the worst case, n will be 100, so it can be considered O(1).
The algorithm uses a constant amount of extra space, regardless of the input size. We only use a few variables to store the tax, previous upper bound, taxable income, and the loop variables. Therefore, the space complexity is O(1).