2021-11-05 Daily-Challenge

Today I have done leetcode's November LeetCoding Challenge with cpp.

November LeetCoding Challenge 5

Description

Arranging Coins

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

Example 1:

img

Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.

Example 2:

img

Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.

 

Constraints:

  • 1 <= n <= 231 - 1

Solution

class Solution {
public:
  int arrangeCoins(int n) {
    long long begin = 0, end = n;
    while(begin < end) {
      long long mid = (begin + end) / 2;
      long long need = (mid + 1LL) * mid / 2;
      if(need < n) {
        begin = mid + 1;
      } else {
        end = mid;
      }
    }
    if(begin * (begin + 1) / 2 > n) begin -= 1;
    return begin;
  }
};

// Accepted
// 1335/1335 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 96.1 % of cpp submissions (5.8 MB)