Skip to content

2303. Calculate Amount Paid in Taxes 👎

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  double calculateTax(vector<vector<int>>& brackets, int income) {
    double ans = 0;
    int prev = 0;

    for (const vector<int>& b : brackets) {
      const int upper = b[0];
      const int percent = b[1];
      if (income < upper)
        return ans + (income - prev) * percent / 100.0;
      ans += (upper - prev) * percent / 100.0;
      prev = upper;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public double calculateTax(int[][] brackets, int income) {
    double ans = 0;
    int prev = 0;

    for (int[] b : brackets) {
      final int upper = b[0];
      final int percent = b[1];
      if (income < upper)
        return ans + (income - prev) * percent / 100.0;
      ans += (upper - prev) * percent / 100.0;
      prev = upper;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def calculateTax(self, brackets: list[list[int]], income: int) -> float:
    ans = 0
    prev = 0

    for upper, percent in brackets:
      if income < upper:
        return ans + (income - prev) * percent / 100.0
      ans += (upper - prev) * percent / 100.0
      prev = upper

    return ans