Cubic Solution
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let max = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < nums.length; i++) {
for (let j = i; j < nums.length; j++) {
let sum = 0;
for (let k = i; k <= j; k++) {
sum += nums[k];
if(sum > max) {
max = sum;
}
}
}
}
return max;
};
This one will give you a Time Limit Exceeded
but I wanted to include it anyway.
Quadratic Solution
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let max = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < nums.length; i++) {
let sum = 0;
for (let j = i; j < nums.length; j++) {
sum += nums[j];
if (sum > max) {
max = sum;
}
}
}
return max;
};
This one will give you a Time Limit Exceeded
but I wanted to include it anyway.
Linear Solution
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let max = nums[0];
let currSum = 0;
for (let i = 0; i < nums.length; i++) {
if (currSum < 0) {
currSum = 0;
}
currSum += nums[i];
max = Math.max(max, currSum);
}
return max;
};
Divide and conquer
TODO
Complexity
TODO