Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmshard

What does Kadane’s algorithm solve?

Tags
#kadane#dynamic-programming#array
Back to categoryPractice quiz

Answer

It finds the maximum sum of a contiguous subarray in O(n) time by tracking the best sum ending at the current position and the best overall.

function maxSubarraySum(nums: number[]): number {
  let best = nums[0];
  let cur = nums[0];

  for (let i = 1; i < nums.length; i++) {
    cur = Math.max(nums[i], cur + nums[i]);
    best = Math.max(best, cur);
  }

  return best;
}

Advanced answer

Deep dive

Kadane’s algorithm is DP in one pass.

Let:

  • cur = best sum of a subarray that must end at i
  • best = best sum seen so far

Transition:

  • cur = max(nums[i], cur + nums[i])
  • best = max(best, cur)

Why it works

If extending the previous subarray makes things worse, you restart at i.

Common pitfalls

  • Initializing best=0 breaks all-negative arrays; start from nums[0].
  • Confusing contiguous subarray with an arbitrary subset.
  • Forgetting you can track indices by remembering when you restart.

Related questions

Algorithms
Boyer–Moore majority vote: what does it solve and what’s the core idea?
#majority-vote#array#linear-time
Algorithms
What does the Floyd–Warshall algorithm compute and what is its complexity?
#graphs#shortest-path#floyd-warshall
Algorithms
Top-down vs bottom-up dynamic programming — what’s the difference?
#dynamic-programming#memoization#tabulation
Algorithms
What is memoization and when does it help?
#memoization#dynamic-programming#cache
Algorithms
Greedy vs dynamic programming — what’s the key difference?
#greedy#dynamic-programming#optimization
Algorithms
What is the two pointers technique?
#two-pointers#array#technique