Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1e2377a

Browse files
Added Maximun Subbarray Problem
1 parent 03a79f2 commit 1e2377a

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

Main.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
var permutationWithoutDuplicates = require("./PermutationsWithoutDuplicates.js");
33
var permutationWithDuplicates = require("./PermutationsWithDuplicates.js");
44
var subsets = require("./Subsets.js");
5+
var maximunSubarray = require("./MaximunSubarray.js");
56

67
// Invocation
78

89
// permutationWithoutDuplicates.main();
910
// permutationWithDuplicates.main();
10-
// subsets.main();
11+
// subsets.main();
12+
maximunSubarray.main();

MaximunSubarray.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
https://leetcode.com/problems/maximum-subarray/submissions/1
3+
4+
. Maximum Subarray
5+
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
6+
7+
Example:
8+
9+
Input: [-2,1,-3,4,-1,2,1,-5,4],
10+
Output: 6
11+
Explanation: [4,-1,2,1] has the largest sum = 6.
12+
Follow up:
13+
14+
*/
15+
16+
var maxSubArray = function(nums) {
17+
if(nums.length == 0) { return 0 };
18+
var maxSub = nums[0];
19+
var currentMax = nums[0];
20+
21+
for(var i = 1; i < nums.length; i++) {
22+
currentMax = max(nums[i], currentMax + nums[i]);
23+
if(currentMax > maxSub) {
24+
maxSub = currentMax;
25+
}
26+
}
27+
28+
return maxSub;
29+
};
30+
31+
var max = function(i, j) {
32+
return (i > j) ? i : j;
33+
}
34+
35+
var main = function() {
36+
console.log(maxSubArray([4,1,-1,4,5,6,7,-200]));
37+
}
38+
39+
module.exports.main = main;

0 commit comments

Comments
 (0)