# Kadane’s Algorithm

![](/files/siDLKInknuljduy7nopJ)

* first try

```jsx
function kadanesAlgorithm(arr) {
  let max = arr[0];
  let sum = arr[0];

  for (let i = 1; i < arr.length; i++) {
    const curr = arr[i];
    const currentSum = sum + curr;
    max = Math.max(currentSum, max, curr);
    sum = Math.max(currentSum, 0);
  }

  return max;
}

// Do not edit the line below.
exports.kadanesAlgorithm = kadanesAlgorithm;
```

* second try
* remove currenSum

```jsx
function kadanesAlgorithm(arr) {
  let max = arr[0];
  let sum = arr[0];

  for (let i = 1; i < arr.length; i++) {
    const curr = arr[i];
    // from this line, if sum < 0, sum = curr
    // basically filter sum less than 0
    sum = Math.max(sum + curr, curr); 
    max = Math.max(sum, max);
  }

  return max;
}

// Do not edit the line below.
exports.kadanesAlgorithm = kadanesAlgorithm;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/kadanes-algorithm.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
