Đề bài
Every person shakes hands once with every other person. A handshake between A and B is the same event as one between B and A. Nobody shakes their own hand.
Implement handshake_count(people).
Input
people: The number of people.
Output
Return the total number of distinct handshakes.
Ràng buộc
0 ≤ people ≤ 1,000,000,000. The answer fits a signed 64-bit integer.
Ví dụ
Đầu vào:
people = 4
Kết quả mong đợi:
expected = 6
Đầu vào:
long long people = 4;
Kết quả mong đợi:
long long expected = 6;
Đầu vào:
long people = 4;
Kết quả mong đợi:
long expected = 6;
Giải thích
The pairs are AB, AC, AD, BC, BD, and CD: six handshakes.
Đầu vào:
people = 1
Kết quả mong đợi:
expected = 0
Đầu vào:
long long people = 1;
Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long people = 1;
Kết quả mong đợi:
long expected = 0;
Giải thích
One person has nobody else to greet.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Each handshake is just an unordered pair of distinct people.
Gợi ý 2
Count how many pairs can be formed from all people without double-counting.
Gợi ý 3
Be careful that zero or one person means no handshakes at all.
Độ phức tạp mong đợi
O(1) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.