Prompt:

Given an array of integers nums, find the subarray with the largest sum and return the sum.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [2,-3,4,-2,2,1,-1,4]
 
Output: 8

Explanation: The subarray [4,-2,2,1,-1,4] has the largest sum 8.

Example 2:

Input: nums = [-1]
 
Output: -1

Constraints:

  • 1 <= nums.length <= 100,000
  • -10,000 <= nums[i] <= 10,000

Solution:

class Solution {
public:
    int maxSubArray(vector<int>& nums) 
    {
        if(nums.size() == 1) return nums[0];
 
        int right = 0;
 
        int returnValue = nums[0];
        int maxOutPut = 0;
 
        while(right < nums.size())
        {
            maxOutPut += nums[right];
 
            //only keep the streak going if our number is greater than the greatest number we have seen
            if(maxOutPut > returnValue)
            {
                returnValue = maxOutPut;
            }
			
			//if your maximum output is less than zero then it cannot be the answer
            if(maxOutPut < 0)
            {
                maxOutPut = 0;
            }
 
			//always increment the right
            right++;
            
        }
 
        return returnValue;
    }
};

Explanation:

Okay so this was one of the first greedy algorithms that I have ever done, and as far as I understand that means that we try to do the most optimal step every single time and never backtrack, and then that will hopefully put us into a solution.

Either way, this one I saw on tiktok, and that way that it works is by following a Kadane’s Algorithm, which is the idea that a negative running sum can only really hurt the total output. Basically if the total sum every goes to a negative value, then that means we can just understand that that given sub-string is not at all helping the total string.

So in essence, if we want to find the greatest sum, if we ever get below zero, then we just restart. Now obviously this makes sense for whenever we have positive values inside of our array. Because we can set our max to zero and then just update it whenever we get past zero. The issue with this is an incoming negative value might fuck things up and make the total go down again. So you keep a second best counter that basically holds the best value you have seen, allowing you to update it whenever you find a new best, but also then zero out your max output whenever you go below zero.

With this, the only edge case that is actually left is if your array is made up of entirely negative numbers, because then you will always just proc that change to zero for your current value. This is why you actually record the lowest value that you have before changing it, so you start your best at the first index in the array, and then if all numbers are negative you always return to zero when the loop is done, so you compare each negative number until you find the one that is the greatest, and why the algorithm works.