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
The solution has a time complexety of [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer.
60
+
Это решение имеет [оценку сложности](https://ru.wikipedia.org/wiki/«O»_большое_и_«o»_малое) O(n<sup>2</sup>). Другими словами, если мы увеличим размер массива в 2 раза, время выполнения алгоритма увеличится в 4 раза.
61
61
62
-
For big arrays (1000, 10000 or more items) such algorithms can lead to a serious sluggishness.
62
+
Для больших массивов(1000, 10000 или больше элементов) такие алгоритмы могут приводить к серьёзным "тормозам".
63
63
64
-
# Fast solution
64
+
# Быстрое решение
65
65
66
-
Let's walk the array and keep the current partial sum of elements in the variable `s`. If`s`becomes negative at some point, then assign `s=0`. The maximum of all such `s`will be the answer.
66
+
Идём по массиву и накапливаем текущую частичную сумму элементов в переменной `s`. Если`s`в какой-то момент становится отрицательной - присваиваем `s=0`. Максимальный из всех `s`и будет ответом.
67
67
68
-
If the description is too vague, please see the code, it's short enough:
68
+
Если объяснение недостаточно понятно, посмотрите на код, он вполне лаконичен:
69
69
70
70
```js run demo
71
71
functiongetMaxSubSum(arr) {
72
72
let maxSum =0;
73
73
let partialSum =0;
74
74
75
-
for (let item of arr) { //for each item of arr
76
-
partialSum += item; //add it to partialSum
77
-
maxSum =Math.max(maxSum, partialSum); //remember the maximum
78
-
if (partialSum <0) partialSum =0; //zero if negative
75
+
for (let item of arr) { //для каждого элемента массива
76
+
partialSum += item; //добавляем значение элемента к partialSum
77
+
maxSum =Math.max(maxSum, partialSum); //запоминаем максимум на данный момент
78
+
if (partialSum <0) partialSum =0; //ноль если отрицательное
The algorithm requires exactly 1 array pass, so the time complexity is O(n).
92
+
Этот алгоритм требует ровно 1 проход по массиву и его оценка сложности O(n).
93
93
94
-
You can find more detail information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words.
94
+
Больше информации об алгоритме тут: [Задача поиска максимальной суммы подмассива](http://en.wikipedia.org/wiki/Maximum_subarray_problem). Если всё ещё не очевидно как это работает, просмотрите алгоритм в примерах выше, это будет лучше всяких слов.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/04-array/5-array-input-sum/solution.md
+3-3Lines changed: 3 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
Please note the subtle, but important detail of the solution. We don't convert`value`to number instantly after`prompt`, because after `value = +value`we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead.
1
+
Обратите внимание на малозаметную, но важную деталь решения. Мы не преобразуем`value`в число сразу после`prompt`, потому что после `value = +value`мы не сможем отличить пустую строку (конец записи) от "0" (разрешённое число). Мы сделаем это позже.
2
2
3
3
4
4
```js run demo
@@ -8,9 +8,9 @@ function sumInput() {
8
8
9
9
while (true) {
10
10
11
-
let value =prompt("A number please?", 0);
11
+
let value =prompt("Введите число", 0);
12
12
13
-
//should we cancel?
13
+
//Прекращаем ввод?
14
14
if (value ===""|| value ===null||!isFinite(value)) break;
0 commit comments