DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

1

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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay