logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
ArraysBoyer-Moore Majority Vote AlgorithmKadane’s AlgorithmTriple Reverse algorithm aka Reversal Algorithm
Cycle detectionDijkstraDisjoint Set UnionGraphTopological SortTraversal algorithmsTree Traversal
Binary HeapBinomial HeapHeap
Cycle DetectionLinked ListSorting
Finding the majority elementRotate array by K steps
Finding If Number is PrimeGCD of two numbersPerforming ExponentiationPrime NumbersRandomising Data
3. Max Consecutive OnesHoare'S Partition SchemeLomuto Partition Scheme
DequesPriority QueueQueue
The Binary Search Master GuideThe Rotated Sorted Array Master Guide
Bubble SortCounting SortInsertion SortMerge SortPigeon Hole SortQuick SortSelection Sort
Monotonic StackMonotonic StackStackReversing an ArrayStackTower of Hanoi
Binary Tree TraversalCentre of gravityDiameter of TreeShortest Path
Algorithmic Pattern/arrays

Kadane’s Algorithm

2 min read
On this pageAlgorithm
AlgorithmStepsCode ComplexityPractice ProblemsReference 

An efficient technique used to find the maximum sum of a contiguous subarray within a given array of numbers. Its beauty lies in its simplicity and its ability to solve the maximum subarray sum problem in linear time complexity O(n)\text{O}(n)O(n)

# Algorithm

The algorithm works by maintaining two variables:

  1. max_ending_here: the maximum sum contiguous subarray ending at the current position.
  2. max_so_far: the maximum sum of contiguous subarray found so far.

The key insight is that maximum subarray ending at each position is either:

  • The current element itself, or
  • The current element plus the maximum subarray ending at the previous position

# Steps

  1. Initialize both max_ending_here and max_so_far with the first element of the array.
  2. Iterate through the array starting from the second element:
  3. For each element, update max_ending_here:
    • If adding the current element to max_ending_here results in a larger sum, keep the sum.
    • Otherwise, start a new subarray from the current element.
  4. Update max_so_far if max_ending_here is greater.
  5. After the iteration, max_so_far will contain the maximum subarray sum.

# Code

# Complexity

Time complexity: O(n), we make only one iterations through the array.
Space complexity: O(1), only two variables.

# Practice Problems

# Reference

  • Kadane’s Algorithm: Mastering the Maximum Subarray Problem


\

←PreviousBoyer-Moore Majority Vote AlgorithmNext→Triple Reverse algorithm aka Reversal Algorithm

On this page

AlgorithmStepsCode ComplexityPractice ProblemsReference