Problem Description
Given a sorted 2D array of tax brackets where each element represents an upper bound and its corresponding tax percentage, calculate the total tax payable on a given income. Each bracket taxes only the portion of income within its range, and the computation stops once the entire income has been processed.
Key Insights
- Iterate through each tax bracket sequentially.
- For each bracket, compute the amount of income that falls into that bracket (using the minimum of the bracket's upper bound and the total income).
- Subtract the part of income already taxed from previous brackets.
- Multiply the taxable amount in the current bracket by the tax rate (converted to a fraction).
- Stop processing when the full income has been taxed.
- Use simulation with constant space to efficiently solve the problem.
Space and Time Complexity
Time Complexity: O(n), where n is the number of tax brackets.
Space Complexity: O(1), using constant extra space.
Solution
The solution involves simulating the tax calculation across tax brackets. We iterate through each bracket and determine:
- The amount of income that should be taxed in the current bracket (by taking the difference between the bracket's upper bound and the previous bracket's upper bound, capped by the total income).
- The tax for that bracket, computed by applying the bracket's tax percentage on the calculated income segment.
- We update the cumulative income taxed and break out of the loop when the taxed amount meets or exceeds the total income. This simulation approach is straightforward and efficient given the problem constraints.