2/29/2024
Maximum SubArray
My approach is to use two pointers: startI and endI. The idea is when you find a subarray whose sum is negative, it's useless because the only thing it can do is to subtract from the element after it, so, we need to eliminate it. So, I use two pointers to iterate over the array. The pointer startI will be at index 0 initially while the pointer endI will be -1. In each iteration, I will increase endI by 1, then add the element at the position of endI to the sum. If the sum is negative, I will move the pointer startI until it is not negative anymore. If startI crosses endI, I will reset the sum to null. The loop stops when endI reach the end of the array.
Revised by ChatGPT
In this problem, we are asked to find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Approach
To solve this problem, I used a two-pointer technique with startI and endI pointers. The key insight is that a subarray with a negative sum will only decrease the sum of any contiguous subarray that includes it. Therefore, such subarrays can be safely ignored.
- Initialization: Start with
startIat index 0 andendIat index -1. This is because we haven't considered any elements yet. InitializesumtonullandmaxSumto-Infinityto handle cases where all numbers are negative. - Iteration: Increment
endIby 1 in each iteration to include the next element in the subarray. Update thesumwith the value of the element atendI. Ifsumis null, it means we are starting a new subarray, so setsumto the current element. - Updating
maxSum: After updatingsum, check if it is greater thanmaxSum. If so, updatemaxSumwith the value ofsum. - Handling Negatvie Sums: If
sumbecomes negative, it means the current subarray will not contribute positively to any larger subarray. Therefore, incrementstartIto exclude elements from the beginning of the subarray untilsumis no longer negative orstartIcrossesendI. IfstartIcrossesendI, resetsumto null. - Termination: The loop continues until
endIreaches the end of the array. - Return: Finally, return
maxSum, which holds the largest sum of any contiguous subarray.
This approach ensures that we only consider subarrays that have the potential to contribute positively to the overall sum, thus efficiently finding the maximum subarray sum.