Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created July 1, 2020 09:03
Show Gist options
  • Select an option

  • Save alldroll/922629165cd758b75460e0840454cf93 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/922629165cd758b75460e0840454cf93 to your computer and use it in GitHub Desktop.
// a1 + a2 + a3 + .. + an = n * (a1 + an) / 2
// 1 + 2 + 3 + 4 + 5
// 5 * (1 + 5) / 2 = 10
func arrangeCoins(n int) int {
i, j := 1, n + 1
for i < j {
h := int(uint64(i + j) >> 1)
sum := (h * (1 + h)) / 2
if sum < n {
i = h + 1
} else {
j = h
}
}
if sum := (i * (1 + i)) / 2; sum > n {
i--
}
return i
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment