DEV Community

Ganga Sri V
Ganga Sri V

Posted on

Kadane's Algorithm

Problem Statement:
You are given an integer array arr[]. You need to find the maximum sum of a subarray (containing at least one element) in the array arr[].

My Approach:

I used Kadane’s Algorithm, which is easy and fast:

1.First I Start with the first number and I use two variables that max that stores the current sum of the subarray ending at this number and res that stores the largest sum found so far.

2.Then I starts from the second number in the array that for each number, I check that is it better to add this number to the previous sum (max + arr[i]) or start a new subarray from this number (arr[i])

3.Then Update max with the bigger value.
4.Then Update the result by comparing the previous res and max.
5.Finally I find res , that gonna be the maximum sum of any continuous subarray.
6.Then I return the res

Methods Used:
Kadane’s Algorithm
Single Traversal
Result Storage

Top comments (0)