From 1e2377a6d5c09642ea10496032985cd48a303e1e Mon Sep 17 00:00:00 2001 From: Ignacio Chiazzo Date: Sun, 21 Oct 2018 16:44:33 -0400 Subject: [PATCH] Added Maximun Subbarray Problem --- Main.js | 4 +++- MaximunSubarray.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 MaximunSubarray.js diff --git a/Main.js b/Main.js index b9011fd..cb00102 100644 --- a/Main.js +++ b/Main.js @@ -2,9 +2,11 @@ var permutationWithoutDuplicates = require("./PermutationsWithoutDuplicates.js"); var permutationWithDuplicates = require("./PermutationsWithDuplicates.js"); var subsets = require("./Subsets.js"); +var maximunSubarray = require("./MaximunSubarray.js"); // Invocation // permutationWithoutDuplicates.main(); // permutationWithDuplicates.main(); -// subsets.main(); \ No newline at end of file +// subsets.main(); +maximunSubarray.main(); \ No newline at end of file diff --git a/MaximunSubarray.js b/MaximunSubarray.js new file mode 100644 index 0000000..62029e9 --- /dev/null +++ b/MaximunSubarray.js @@ -0,0 +1,39 @@ +/* +https://leetcode.com/problems/maximum-subarray/submissions/1 + +. Maximum Subarray +Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. + +Example: + +Input: [-2,1,-3,4,-1,2,1,-5,4], +Output: 6 +Explanation: [4,-1,2,1] has the largest sum = 6. +Follow up: + +*/ + +var maxSubArray = function(nums) { + if(nums.length == 0) { return 0 }; + var maxSub = nums[0]; + var currentMax = nums[0]; + + for(var i = 1; i < nums.length; i++) { + currentMax = max(nums[i], currentMax + nums[i]); + if(currentMax > maxSub) { + maxSub = currentMax; + } + } + + return maxSub; +}; + +var max = function(i, j) { + return (i > j) ? i : j; +} + +var main = function() { + console.log(maxSubArray([4,1,-1,4,5,6,7,-200])); +} + +module.exports.main = main; \ No newline at end of file