logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
arrays
Arrays
Boyer-Moore Majority Vote Algorithm
Kadane’s Algorithm
Triple Reverse algorithm aka Reversal Algorithm
graph
Cycle detection
Graph
Topological Sort
Tree Traversal
heap
Binary Heap
Binomial Heap
Heap
linked-list
Cycle Detection
Linked List
Sorting
miscellaneous
Finding the majority element
Rotate array by K steps
numerical-algorithms
Finding If Number is Prime
GCD of two numbers
Performing Exponentiation
Prime Numbers
Randomising Data
partitioning
3. Max Consecutive Ones
Hoare'S Partition Scheme
Lomuto Partition Scheme
queue
Deques
Priority Queue
Queue
search
The Binary Search Master Guide
The Rotated Sorted Array Master Guide
sort
Bubble Sort
Counting Sort
Sorting
Insertion Sort
Merge Sort
Pigeon Hole Sort
Quick Sort
Selection Sort
stack
Monotonic Stack
Monotonic Stack
Stack
Reversing an Array
Stack
Tower of Hanoi
tree
Binary Tree Traversal
Centre of gravity
Diameter of Tree
Shortest Path
Algorithmic Pattern›arrays

Kadane’s Algorithm

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 AlgorithmNextTriple Reverse algorithm aka Reversal Algorithm
CONTENTS
AlgorithmStepsCode ComplexityPractice ProblemsReference