LeetCode 829. Consecutive Numbers Sum
原题链接
困难
作者:
JasonSun
,
2020-01-16 13:33:30
,
所有人可见
,
阅读 778
Algorithm (Math)
- Suppose that there exists an $0\leq x<N$ such that $\sum_{j=0}^{k}(x+j)=N.$ Then note that for any $0\leq k<N$, we have that 5 , 5 + 1, 5 + 2, $$\begin{aligned}
\sum_{j=0}^{k}(x+j) & =\frac{(2x+k)\cdot(k+1)}{2}=x(k+1)+\frac{1}{2}(k^{2}+k)=N,\end{aligned}$$ which after rearranging yield $$x(k+1)=N-\frac{1}{2}k(k+1).$$
- So to design an algorithm, we simply need to enumerate $k$ and check if $k+1$ divides $N-\frac{1}{2}k(k+1).$
- To speed things up, we work out a tighter search range of $k$. Note that we can easily get the following inequalities $$N-\frac{k}{2}(k+1)=x(k+1)>k+1$$ since $x\geq1$, which also implies that $2N>k(k+1)>k^{2};$ so we have $0\,<k\leq\sqrt{2N}.$
Code
class Solution {
public:
int consecutiveNumbersSum(int N) {
return [&](int acc = 0) {
for (int k = 0; k < sqrt(2 * N); ++k)
if ((N - k * (k + 1) / 2) >= k + 1 and (N - k * (k + 1) / 2) % (k + 1) == 0)
acc++;
return acc;
}();
}
};
%%