LEARNING JOURNAL

I created this learning journal to practice writting and to help me learn by writting everything down. Source code here

2/29/2024

Maximum SubArray

THE PROBLEM

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 startI at index 0 and endI at index -1. This is because we haven't considered any elements yet. Initialize sum to null and maxSum to -Infinity to handle cases where all numbers are negative.
  • Iteration: Increment endI by 1 in each iteration to include the next element in the subarray. Update the sum with the value of the element at endI. If sum is null, it means we are starting a new subarray, so set sum to the current element.
  • Updating maxSum: After updating sum, check if it is greater than maxSum. If so, update maxSum with the value of sum.
  • Handling Negatvie Sums: If sum becomes negative, it means the current subarray will not contribute positively to any larger subarray. Therefore, increment startI to exclude elements from the beginning of the subarray until sum is no longer negative or startI crosses endI. If startI crosses endI, reset sum to null.
  • Termination: The loop continues until endI reaches 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.