Skip to content

Commit dd2db02

Browse files
committed
issue#171: maxArraySum Problem
1 parent 854b6cb commit dd2db02

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/_Problems_/max-array-sum/index.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
function maxArraySum(array, n) {
2+
if (array.length == 0) {
3+
return "null as the length of array is nil.";
4+
}
5+
else if (array.length < n) {
6+
var str = "null as the length of subarray is less than " + n + ".";
7+
return str;
8+
}
9+
else if (array.length == n) {
10+
var sum = array.reduce(function (a, b) {
11+
return a + b;
12+
}, 0);
13+
return sum;
14+
}
15+
else if (array.length > n) {
16+
var i, j, max;
17+
for (i = 0; i < 1; i++) {
18+
var temp = [];
19+
for (j = i; j < i + n; j++) {
20+
temp.push(array[j]);
21+
}
22+
var sum = temp.reduce(function (a, b) {
23+
return a + b;
24+
}, 0);
25+
max = sum;
26+
}
27+
for (i = 1; i <= array.length - n; i++) {
28+
var temp = [];
29+
for (j = i; j < i + n; j++) {
30+
temp.push(array[j]);
31+
}
32+
var sum = temp.reduce(function (a, b) {
33+
return a + b;
34+
}, 0);
35+
if (sum > max) {
36+
max = sum;
37+
}
38+
}
39+
return max;
40+
}
41+
}
42+
43+
module.exports = {
44+
maxArraySum,
45+
};
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const { maxArraySum } = require('.');
2+
3+
describe('Max Array Sum', () => {
4+
it('Should return 10', () => {
5+
expect(maxArraySum([1, 5, 2, 3, 4], 3)).toEqual(10);
6+
});
7+
8+
it('Should return 1', () => {
9+
expect(maxArraySum([1, 2, 4], 4)).toEqual("null as the length of subarray is less than 4.");
10+
});
11+
12+
it('Should return 120', () => {
13+
expect(maxArraySum([], 2)).toEqual("null as the length of array is nil.");
14+
});
15+
});

0 commit comments

Comments
 (0)