Problem

Initially, you have a bank account balance of 100 dollars.

You are given an integer purchaseAmount representing the amount you will spend on a purchase in dollars, in other words, its price.

When making the purchase, first the purchaseAmount is rounded to the nearest multiple of 10. Let us call this value roundedAmount. Then, roundedAmount dollars are removed from your bank account.

Return an integer denoting your final bank account balance after this purchase.

Notes:

  • 0 is considered to be a multiple of 10 in this problem.
  • When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on).

Examples

Example 1:

1
2
3
4
Input: purchaseAmount = 9
Output: 90
Explanation:
The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90.

Example 2:

1
2
3
4
Input: purchaseAmount = 15
Output: 80
Explanation:
The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80.

Example 3:

1
2
3
4
Input: purchaseAmount = 10
Output: 90
Explanation:
10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.

Constraints:

  • 0 <= purchaseAmount <= 100

Solution

Method 1 – Rounding to Nearest Multiple of 10

Intuition

The key idea is to round the purchase amount to the nearest multiple of 10, subtract it from the initial balance (100), and return the result. Rounding is done such that values ending in 5 or more round up (e.g., 15 → 20), and less than 5 round down (e.g., 13 → 10).

Approach

  1. Start with a balance of 100.
  2. To round purchaseAmount to the nearest multiple of 10:
  • Add 5 to purchaseAmount and perform integer division by 10, then multiply by 10.
  • This ensures numbers ending in 5 or more round up.
  1. Subtract the rounded amount from the balance.
  2. Return the result.

Code

1
2
3
4
5
6
7
8
class Solution {
public:
   int accountBalanceAfterPurchase(int purchaseAmount) {
      int rounded = ((purchaseAmount + 5) / 10) * 10;
      int ans = 100 - rounded;
      return ans;
   }
};
1
2
3
4
5
6
7
class Solution {
   public int accountBalanceAfterPurchase(int purchaseAmount) {
      int rounded = ((purchaseAmount + 5) / 10) * 10;
      int ans = 100 - rounded;
      return ans;
   }
}
1
2
3
4
5
class Solution:
   def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
      rounded: int = ((purchaseAmount + 5) // 10) * 10
      ans: int = 100 - rounded
      return ans

Complexity

  • ⏰ Time complexity: O(1) — Only basic arithmetic operations.
  • 🧺 Space complexity: O(1) — No extra space used.