From 33e08828b061321c4fe9181c2f5b0171e189e3d7 Mon Sep 17 00:00:00 2001 From: dainik10 Date: Sat, 28 Oct 2023 13:34:18 +0530 Subject: [PATCH 1/2] Maximum Subarray Updated --- DSA/Arrays/Maximumsubarray.js | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/DSA/Arrays/Maximumsubarray.js b/DSA/Arrays/Maximumsubarray.js index fc2247e..f3a7a8b 100644 --- a/DSA/Arrays/Maximumsubarray.js +++ b/DSA/Arrays/Maximumsubarray.js @@ -1,12 +1,18 @@ -var maxSubArray = function(nums) { - var prev = 0; - var max = -Infinity; - - for (var i = 0; i < nums.length; i++) { - // Compare previous contiguous sum with current number - prev = Math.max(prev + nums[i], nums[i]); - // Check if the current prev is the greatest sum - max = Math.max(max, prev); - } - return max; -}; +const maxSubArray = (nums) => { + // initiate two variable, maxSum for total max, sum for current max + let maxSum = -Infinity + let currentSum = 0 + // iterate through the nums, store sub-problems result + for(let i = 0; i < nums.length; i++){ + //cumulating answers to the top + + //compare currentSum add current number + //with current number and store the maximum value + currentSum = Math.max(nums[i], currentSum + nums[i]) + + //compare maxSum with currentSum and store the greater value + maxSum = Math.max(currentSum, maxSum) + + } + return maxSum +} \ No newline at end of file From 9df9b9ad207efcaf04fe84bb4840b7108f678daa Mon Sep 17 00:00:00 2001 From: dainik10 Date: Sat, 28 Oct 2023 13:48:19 +0530 Subject: [PATCH 2/2] Created Insertion Sort as Insertionsort.js file --- DSA/Arrays/Insertionsort.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 DSA/Arrays/Insertionsort.js diff --git a/DSA/Arrays/Insertionsort.js b/DSA/Arrays/Insertionsort.js new file mode 100644 index 0000000..6fdfe9d --- /dev/null +++ b/DSA/Arrays/Insertionsort.js @@ -0,0 +1,12 @@ +function insertionSort(arr) { + for (let i = 1; i < arr.length; i++) { + let currentValue = arr[i] + let j + for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { + arr[j + 1] = arr[j] + } + arr[j + 1] = currentValue + } + return arr +} +console.log(insertionSort([2, 1, 3, 7, 5])) // [1, 2, 3, 5, 7] \ No newline at end of file