I will quote part of your answer with a slight correction:
Let's say that our input array is
4
4. We can create1
contigous1 contiguous subarray of length4
;2
contigous4; 2 contiguous subarrays of length3
;3
contigous3; 3 contiguous subarrays of length2
2, and4
contigous4 contiguous subarrays of length1
1. In other words, the number of contigouscontiguous subarrays for an array of lengthn
$n$ is the sum of1
$1$ ton
$n$, or(n * (n + 1)) / 2
$n(n+1)/2$.
Time Complexity:
Each subarray sum takes O(n)
$O(n)$ to compute and there are (n * (n + 1)) / 2
$n(n+1)/2$ subarrays, hence the asymptotic time, is O(n^3)
i$O(n\cdot n(n+1)/2) = O(n^3)$.e n((n * (n + 1)) / 2)
See inline comments in your code too:
function maxSubArray(arr) {
let max = null;
for (let i = 0; i < arr.length; i++) { // O(n)
const startIdx = i;
for (let j = i; j < arr.length; j++) { // O(n)
let sum = 0;
for (let k = i; k <= j; k++) { // O(n)
sum = sum + arr[k];
}
if (max === null || max < sum) {
max = sum;
}
}
}
return max;
}
For example if arr = [4, -1, 2, 1]
$\mathrm{arr} = [4, -1, 2, 1]$,notice notice that at some point we do traverse the entire array of length n
$n$:
subarray, sum
[4], 4
[4, -1], 3
[4, -1, 2], 5
[4, -1, 2, 1], 6
[-1], -1
[-1, 2], 1
[-1, 2, 1], 2
[2], 2
[2, 1], 3
[1], 1
max_sum = 6