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/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README_EN.md
+33-14
Original file line number
Diff line number
Diff line change
@@ -59,9 +59,9 @@ It can be proven that there is no k-avoiding array with a sum less than 3.
59
59
60
60
### Solution 1: Greedy + Simulation
61
61
62
-
We start from the positive integer $i=1$, and judge whether $i$ can be added to the array in turn. If it can be added, we add $i$ to the array, accumulate it to the answer, and then mark $k-i$ as visited, indicating that $k-i$ cannot be added to the array. The loop continues until the length of the array is $n$.
62
+
Starting from the positive integer $i = 1$, we sequentially determine if $i$ can be added to the array. If it can be added, we add $i$ to the array, accumulate it to the answer, and then mark $k - i$ as visited, indicating that $k-i$ cannot be added to the array. We continue this process until the array's length reaches $n$.
63
63
64
-
The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array.
64
+
The time complexity is $O(n + k)$, and the space complexity is $O(n + k)$. Where $n$ is the length of the array.
65
65
66
66
<!-- tabs:start -->
67
67
@@ -75,9 +75,9 @@ class Solution:
75
75
for _ inrange(n):
76
76
while i in vis:
77
77
i +=1
78
-
vis.add(i)
79
78
vis.add(k - i)
80
79
s += i
80
+
i +=1
81
81
return s
82
82
```
83
83
@@ -87,16 +87,15 @@ class Solution:
87
87
classSolution {
88
88
publicintminimumSum(intn, intk) {
89
89
int s =0, i =1;
90
-
boolean[] vis =newboolean[k+n * n+1];
90
+
boolean[] vis =newboolean[n+k+1];
91
91
while (n-->0) {
92
92
while (vis[i]) {
93
93
++i;
94
94
}
95
-
vis[i] =true;
96
95
if (k >= i) {
97
96
vis[k - i] =true;
98
97
}
99
-
s += i;
98
+
s += i++;
100
99
}
101
100
return s;
102
101
}
@@ -110,17 +109,16 @@ class Solution {
110
109
public:
111
110
int minimumSum(int n, int k) {
112
111
int s = 0, i = 1;
113
-
bool vis[k + n * n + 1];
112
+
bool vis[n + k + 1];
114
113
memset(vis, false, sizeof(vis));
115
114
while (n--) {
116
115
while (vis[i]) {
117
116
++i;
118
117
}
119
-
vis[i] = true;
120
118
if (k >= i) {
121
119
vis[k - i] = true;
122
120
}
123
-
s += i;
121
+
s += i++;
124
122
}
125
123
return s;
126
124
}
@@ -132,16 +130,16 @@ public:
132
130
```go
133
131
func minimumSum(n int, k int) int {
134
132
s, i := 0, 1
135
-
vis := make([]bool, k+n*n+1)
133
+
vis := make([]bool, n+k+1)
136
134
for ; n > 0; n-- {
137
135
for vis[i] {
138
136
i++
139
137
}
140
-
vis[i] = true
141
138
if k >= i {
142
139
vis[k-i] = true
143
140
}
144
141
s += i
142
+
i++
145
143
}
146
144
return s
147
145
}
@@ -153,21 +151,42 @@ func minimumSum(n int, k int) int {
0 commit comments