Skip to content

Instantly share code, notes, and snippets.

@chunrapeepat
Last active February 17, 2021 05:44
Show Gist options
  • Save chunrapeepat/8a905b9d091bf69c31fe4591a3fcee14 to your computer and use it in GitHub Desktop.
Save chunrapeepat/8a905b9d091bf69c31fe4591a3fcee14 to your computer and use it in GitHub Desktop.
DAY9 - Dynamic Programming - Maximum Subarray Solution
// top-down approach
function maxSubarray(arr) {
const memo = {};
let answer = Number.MIN_VALUE;
function _maxSubarray(arr, i) {
// base case
if (arr.length === 0) return 0;
if (i === 0) return arr[0];
// induction case
if (memo[i]) return memo[i];
memo[i] = Math.max(_maxSubarray(arr, i - 1) + arr[i], arr[i]);
// update answer (find max)
if (memo[i] > answer) {
answer = memo[i];
}
return memo[i];
}
_maxSubarray(arr, arr.length - 1);
return answer;
}
// bottom-up approach
function maxSubarray(arr) {
// base case
if (arr.length === 0) return 0;
const memo = {};
memo[0] = arr[0];
// induction case
let answer = Number.MIN_VALUE;
for (let i = 1; i < arr.length; ++i) {
memo[i] = Math.max(memo[i-1] + arr[i], arr[i]);
if (memo[i] > answer) {
answer = memo[i];
}
}
return answer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment