maxSubsequence
that takes in an array of numbers and returns the maximum sum.For example, given the array [-2, 5, 2, -1, 3, -1]
, the maximum sum subarray is [5, 2, -1, 3]
, which has a sum of 9. Therefore, maxSubsequence([-2, 5, 2, -1, 3, -1])
should return 9.To solve this problem, we can use the "contains algorithm," which has a time complexity of O(n). We will loop through the array and look for all positive, contiguous subarrays, keeping track of the maximum sum as we go. We start with a current maximum and a maximum so far, both set to 0.
We then iterate over each element in the array and calculate the current maximum by taking the maximum of either 0 or the current maximum plus the current element. We also update the maximum so far by taking the maximum of either the current maximum or the maximum so far. This way, we keep track of the largest sum that we have seen so far.
After iterating over the entire array, we return the maximum so far, which represents the largest possible sum of a subarray.
Here's the code for themaxSubsequence
function:function maxSubsequence(arr) {
let currentMax = 0;
let maxSoFar = 0;
for (let i = 0; i < arr.length; i++) {
currentMax = Math.max(0, currentMax + arr[i]);
maxSoFar = Math.max(currentMax, maxSoFar);
}
return maxSoFar;
}
The function first initializes the current maximum and the maximum so far to 0. Then it loops through each element in the array and updates the current maximum and maximum so far. Finally, it returns the maximum so far, which represents the largest possible sum of a subarray.
Big O Complexity Analysis:
The time complexity of themaxSubsequence
function is O(n), where n is the length of the input array. This is because we loop through the array once, and each iteration takes constant time.The space complexity is O(1), because we only use a fixed amount of memory to store the current maximum and maximum so far. We do not create any new data structures, so the space used by the program is constant.