DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

Maximum subarray

I will be talking about the maximum subarray leetCode problem.

Let`s set up the problem.

At first it was a little hard for me to understand how to actually do it cause i did not understand what was being asked and i was over engineering it, so it is really important to understand what we have to do before start coding.

We are being asked to find the subarray with the largest sum.

Examples given by leetCode:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23

We will have to define two main variables, one to store the value that should always be smaller that the actual value we have to check and in order to do that we will have to use "Infinity" which in positive will always be greater than any other value and in negative will be the opposite.

Image description

Next we will have to make two loops that will over the array, will re-define the currSum and if it is greater than maxSum we sill re-define maxSum with the currSum value.

Image description

On the last for loop we will make an if statement that will check if maxSum is smallet than currSum and if it is, we will re define maxSum with the currSum value.

Finally the code will look like this.

Image description

If you have any further questions, i will happy to help you out.

Hope someone found it helpful.

Lautaro.

Top comments (0)