You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/2100-2199/2195.Append K Integers With Minimal Sum/README_EN.md
+47-48
Original file line number
Diff line number
Diff line change
@@ -41,49 +41,44 @@ The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return
41
41
42
42
## Solutions
43
43
44
-
### Solution 1
44
+
### Solution 1: Sorting + Greedy + Mathematics
45
+
46
+
We can add two sentinel nodes to the array, which are $0$ and $2 \times 10^9$.
47
+
48
+
Then we sort the array. For any two adjacent elements $a$ and $b$ in the array, the integers in the interval $[a+1, b-1]$ do not appear in the array, and we can add these integers to the array.
49
+
50
+
Therefore, we traverse the adjacent element pairs $(a, b)$ in the array from small to large. For each adjacent element pair, we calculate the number of integers $m$ in the interval $[a+1, b-1]$. The sum of these $m$ integers is $\frac{m \times (a+1 + a+m)}{2}$. We add this sum to the answer and subtract $m$ from $k$. If $k$ is reduced to $0$, we can stop the traversal and return the answer.
51
+
52
+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array.
0 commit comments