Input: brackets = [[3,50],[7,10],[12,25]], income = 10
Output: 2.65000
Explanation:
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.
Input: brackets = [[1,0],[4,25],[5,50]], income = 2
Output: 0.25000
Explanation:
Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.
The tax rate for the two tax brackets is 0% and 25%, respectively.
In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.
Input: brackets = [[2,50]], income = 0
Output: 0.00000
Explanation:
You have no income to tax, so you have to pay a total of $0 in taxes.
1.for문을 돌면서 현재 bound - 이전 bound 값을 current 로 저장한다.
2. income >= current 라면 income -= current 를 해주고 tax에 더해준다. 그 다음 prev를 갱신해준다.
3. income < current 라면 tax에 일단 더해준다음 income을 0으로 만들어준다.
/**
* @param {number[][]} brackets
* @param {number} income
* @return {number}
*/
const calculateTax = function (brackets, income) {
let prev = 0;
let current = 0;
let tax = 0;
for (let i = 0; i < brackets.length; i++) {
current = brackets[i][0] - prev; // upperi - upper0
if (income >= current) {
// income 이 current 값보다 크다면 income에서 current를 빼주고 current * tax 비율 더해준다
income -= current;
tax += current * brackets[i][1];
prev = brackets[i][0];
} else {
// 아니라면 income을 0으로 만들고 더해준다
tax += income * brackets[i][1];
prev = brackets[i][0];
income = 0;
}
}
return (tax / 100).toFixed(5);
};
