Coding Interview Questions | Maximum Subarray
January 5th, 2024
Contains Duplicate Problem Introduction:
This summary will talk about my solution to the maximum subarray problem as seen on leetcode here.
How do you solve the Maximum Subarrary Problem in O(n) time?:
Solution:
function maxSubArray(nums: number[]): number {
if (nums.length === 1) {
return nums[0];
}
const maxSums = Array.from(nums, () => 0);
maxSums[0] = nums[0];
// Create array of maximum sums
for (let numIdx = 1; numIdx < maxSums.length; numIdx++) {
const currentNum = nums[numIdx];
maxSums[numIdx] = Math.max(currentNum, currentNum + maxSums[numIdx - 1]);
}
return Math.max(...maxSums);
}
Maximum Subarray Solution Summary:
Below is a breakdown of the key aspects of the solution above:
- Base Case Handling: The algorithm checks if the length of the input array (
nums
) is 1. If true, it directly returns the only element in the array as the maximum subarray sum. - Dynamic Programming Approach: The solution utilizes a dynamic programming approach, creating an array (
maxSums
) to store the maximum sum at each index. - Maximum Sum Calculation: The algorithm iterates through the array, updating
maxSums
at each index with the maximum sum considering the current element and the maximum sum from the previous index. - Final Maximum Subarray Sum Determination: The final result is determined by finding the maximum value in the
maxSums
array.
Complexities
- Time Complexity: The time complexity of the solution is
O(n)
, wheren
is the length of the input array. - Space Complexity: The space complexity of the solution is
O(n)
as it uses an additional array (maxSums
) of the same length as the input array.