ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Count Handshakes

Count handshakes when every pair of people shakes hands once.

สิ่งที่คุณจะได้เรียนรู้

  • Count pairs with n × (n - 1) / 2
  • Reason about counting each pair once
  • Replace a loop with a formula

โจทย์

ดูฉบับแปล

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.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
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.

ตัวอย่างที่ 2
อินพุต:
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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก