โจทย์
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.
เงื่อนไข
0 ≤ people ≤ 1,000,000,000. The answer fits a signed 64-bit integer.
ตัวอย่าง
อินพุต:
people = 4
ผลลัพธ์ที่คาดหวัง:
expected = 6
อินพุต:
long long people = 4;
ผลลัพธ์ที่คาดหวัง:
long long expected = 6;
อินพุต:
long people = 4;
ผลลัพธ์ที่คาดหวัง:
long expected = 6;
คำอธิบาย
The pairs are AB, AC, AD, BC, BD, and CD: six handshakes.
อินพุต:
people = 1
ผลลัพธ์ที่คาดหวัง:
expected = 0
อินพุต:
long long people = 1;
ผลลัพธ์ที่คาดหวัง:
long long expected = 0;
อินพุต:
long people = 1;
ผลลัพธ์ที่คาดหวัง:
long expected = 0;
คำอธิบาย
One person has nobody else to greet.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Each handshake is just an unordered pair of distinct people.
คำใบ้ 2
Count how many pairs can be formed from all people without double-counting.
คำใบ้ 3
Be careful that zero or one person means no handshakes at all.
ความซับซ้อนที่คาดหวัง
O(1) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน