[LeetCode] Calculate Amount Paid in Taxes

2303. Calculate Amount Paid in Taxes

You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).

Tax is calculated as follows:

  • The first upper0 dollars earned are taxed at a rate of percent0.
  • The next upper1 - upper0 dollars earned are taxed at a rate of percent1.
  • The next upper2 - upper1 dollars earned are taxed at a rate of percent2.
  • And so on.

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. Answers within 10-5 of the actual answer will be accepted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
double calculateTax(vector<vector<int>>& brackets, int income) {
bool overIncome = false;
int prv = 0;
double res = 0;
for(auto& b : brackets) {
if(overIncome) break;
int u = b[0], p = b[1];
int benefit = min(u,income) - prv;
res += benefit * p * 1.0 / 100;
prv = u;
if(u >= income) overIncome = true;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/12/PS/LeetCode/calculate-amount-paid-in-taxes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.