From 7626a77ce7abf5a1cf7089476656b7a9b81aaa0d Mon Sep 17 00:00:00 2001 From: Nishant Agrawal <41500636+nishantagrawal01@users.noreply.github.com> Date: 2021年10月30日 16:22:46 +0530 Subject: [PATCH] Create Maximum-Sum-Subarray-[Kadanes-Algorithm] --- .../Maximum-Sum-Subarray-[Kadanes-Algorithm] | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Data-Structures/Array/Maximum-Sum-Subarray-[Kadanes-Algorithm] diff --git a/Data-Structures/Array/Maximum-Sum-Subarray-[Kadanes-Algorithm] b/Data-Structures/Array/Maximum-Sum-Subarray-[Kadanes-Algorithm] new file mode 100644 index 0000000000..c78c6c11ef --- /dev/null +++ b/Data-Structures/Array/Maximum-Sum-Subarray-[Kadanes-Algorithm] @@ -0,0 +1,23 @@ +/* +Given an array of integers containing positive as well as negative integers. Find the sum of subarray which has maximum sum, in the given array. + +Input : 2,-3,4,5,-1 +Output : 9 (Subarray - [2,3]) + +This is O(N) in time complexity. +*/ + +let findMaxSumSubarray = (arr) => { + let final_max = arr[0]; + let curr_max = arr[0]; + + for (let i = 1; i < arr.length; i++) { + let current = arr[i]; + final_max = Math.max(current, current + final_max); + curr_max = Math.max(curr_max, final_max); + } + return curr_max; +}; + +let res = findMaxSumSubarray([2,-3,4,5,-1]); +console.log(res);