Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit857b3be

Browse files
authored
Merge pull requestmgechev#138 from emyarod/maximum-subarray-linear-time
O(n) Maximum subarray bugfix and tests
2 parents53256ef +1fe106d commit857b3be

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

‎src/searching/maximum-subarray.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,10 @@
2020
*@return {Number} Maximum sum of the elements of a subarray.
2121
*/
2222
functionmaxSubarray(array){
23-
varcurrentMax=0;
24-
varmax=0;
25-
26-
for(vari=0;i<array.length;i+=1){
27-
currentMax=Math.max(0,currentMax+array[i]);
23+
varcurrentMax=array[0];
24+
varmax=array[0];
25+
for(vari=1;i<array.length;i+=1){
26+
currentMax=Math.max(array[i],currentMax+array[i]);
2827
max=Math.max(max,currentMax);
2928
}
3029
returnmax;
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
varmaxSubArray=require('../../src/searching/maximum-subarray').maxSubarray;
2+
3+
describe('Maximum subarray',function(){
4+
'use strict';
5+
6+
it('should work with empty arrays',function(){
7+
expect(maxSubArray([])).toBeUndefined();
8+
});
9+
10+
it('should return the only element when an array with single element is passed',function(){
11+
expect(maxSubArray([42])).toBe(42);
12+
});
13+
14+
it('should return the only negative element when an array with single element is passed',function(){
15+
expect(maxSubArray([-42])).toBe(-42);
16+
});
17+
18+
it('should return the zero when an array with single element, which is zero is passed',function(){
19+
expect(maxSubArray([0])).toBe(0);
20+
});
21+
22+
it('should return the max sum of a subarray',function(){
23+
expect(maxSubArray([1,-1,2,3,-1])).toBe(5);
24+
});
25+
26+
it('should return the max negative number when array with negative numbers is provided',function(){
27+
expect(maxSubArray([-10,-1,-2,-3,-1])).toBe(-1);
28+
});
29+
});

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp