LeetCode: Week 1-Maximum Subarray

Jayram Manale
2 min readApr 19, 2020

--

30-day leet coding challenge

Code Solution:

Time Complexity: O(n) | Space Complexity: O(1)

Explanation:

For this problem, we’ll be using Kadane’s algorithm.

we’ll be initializing two variable maxNumSoFar and maxValuewhich will assign the num[0] element to start.

we’ll be keeping track maxNumSoFar where will be comparing nums[i] the value with nums[i] + maxNumSoFar and whichever is greater will assign it to maxNumSoFar .

In maxValue will be comparing maxValue and maxNumSoFar and whichever is greater will assign to maxValue . This is important to remember max value as we traverse each element in the array. In the end, maxValue it will hold the largest sum.

Let's understand how the given array of the element [-2,1,-3,1,-5,4] will run each Iteration and get the output as 4. We’ll be starting iterating array from index 1

Run Code:

You can also check out other problem solution below

I hope you enjoy this solution. Let me know if you have any other solutions in response. Cheers :)

--

--