Skip to content

1716. Calculate Money in Leetcode Bank 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int totalMoney(int n) {
    const int weeks = n / 7;
    const int firstWeek = trapezoid(1, 7);
    const int lastFullWeek = trapezoid(1 + weeks - 1, 7 + weeks - 1);
    const int remainingDays = trapezoid(1 + weeks, n % 7 + weeks);
    return (firstWeek + lastFullWeek) * weeks / 2 + remainingDays;
  }

  // Returns sum(a..b).
  int trapezoid(int a, int b) {
    return (a + b) * (b - a + 1) / 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int totalMoney(int n) {
    final int weeks = n / 7;
    final int firstWeek = trapezoid(1, 7);
    final int lastFullWeek = trapezoid(1 + weeks - 1, 7 + weeks - 1);
    final int remainingDays = trapezoid(1 + weeks, n % 7 + weeks);
    return (firstWeek + lastFullWeek) * weeks / 2 + remainingDays;
  }

  // Returns sum(a..b).
  private int trapezoid(int a, int b) {
    return (a + b) * (b - a + 1) / 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def totalMoney(self, n: int) -> int:
    def trapezoid(a: int, b: int) -> int:
      """Returns sum(a..b)."""
      return (a + b) * (b - a + 1) // 2

    weeks = n // 7
    firstWeek = trapezoid(1, 7)
    lastFullWeek = trapezoid(1 + weeks - 1, 7 + weeks - 1)
    remainingDays = trapezoid(1 + weeks, n % 7 + weeks)
    return (firstWeek + lastFullWeek) * weeks // 2 + remainingDays