Torna alle sfide
Facile 0 risolte 0% di accettazione

Count Handshakes

Count handshakes when every pair of people shakes hands once.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

0 ≤ people ≤ 1,000,000,000. The answer fits a signed 64-bit integer.

Esempi

Esempio 1
Input:
people = 4

Output atteso:
expected = 6
Input:
long long people = 4;

Output atteso:
long long expected = 6;
Input:
long people = 4;

Output atteso:
long expected = 6;

Spiegazione

The pairs are AB, AC, AD, BC, BD, and CD: six handshakes.

Esempio 2
Input:
people = 1

Output atteso:
expected = 0
Input:
long long people = 1;

Output atteso:
long long expected = 0;
Input:
long people = 1;

Output atteso:
long expected = 0;

Spiegazione

One person has nobody else to greet.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Each handshake is just an unordered pair of distinct people.

Suggerimento 2

Count how many pairs can be formed from all people without double-counting.

Suggerimento 3

Be careful that zero or one person means no handshakes at all.

Complessità attesa

O(1) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.