Skip to content

Instantly share code, notes, and snippets.

@kkchu791
Last active March 18, 2019 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkchu791/cf5e09d4604d10b8c31fad65df85a263 to your computer and use it in GitHub Desktop.
Save kkchu791/cf5e09d4604d10b8c31fad65df85a263 to your computer and use it in GitHub Desktop.
linear solving of maximum subarray problem (dynamic programming)
// 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:
// If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
const maxSubArray = (nums) => {
if (nums.length === 1) {
return nums[0];
}
let prevSum = nums[0];
let max = nums[0];
for (let i = 1; i < nums.length; i++) {
prevSum = nums[i] + (prevSum <= 0 ? 0 : prevSum);
max = prevSum > max ? prevSum : max;
}
return max;
};
//is this an optimal solution?
// this solution is O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment