Lost Treasure of Arrayland: A Story of Maximum Subsegment Sum
Learn Kadane’s Algorithm with C++, Java, and Python
The Tale Begins…
In the mystical land of Arrayland, a wandering adventurer comes across a long path of numbers — each number represents treasure (+ve) or traps (-ve) scattered across a magical trail. The adventurer wants to travel only once, choosing a continuous path that gives the maximum net treasure without turning back.
However, if all paths are filled with traps (negative numbers), he decides not to go at all — choosing 0 treasure instead.
Can you help our adventurer find this maximum treasure?
Problem Statement
Given a sequence of
n
integers (which may be negative), find the maximum sum of any consecutive sub-segment.
If all sub-segment sums are negative, return0
.
Input Format
- A single line with
n
followed byn
integers. 1 ≤ n < 1000
- Each number:
|ai| < 10000
Output Format
- A single integer: maximum subsegment sum (or 0 if all sums are negative).
Sample Input
6 -2 11 -4 13 -5 -2
Sample Output
20
Explanation
The best path is [11, -4, 13]
, which sums to 20.
Kadane’s Algorithm: The Secret Spell
This efficient algorithm walks the path just once (O(n)) and keeps track of:
current_sum
: current running total (reset if it drops below 0)max_sum
: highest sum encountered
C++ Implementation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
while (cin >> n) {
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
int current_sum = 0, max_sum = 0;
for (int i = 0; i < n; i++) {
current_sum += arr[i];
if (current_sum < 0) current_sum = 0;
max_sum = max(max_sum, current_sum);
}
cout << max_sum << endl;
}
return 0;
}
Java Implementation
import java.util.Scanner;
public class MaxSubsegmentSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
int currentSum = 0, maxSum = 0;
for (int num : arr) {
currentSum += num;
if (currentSum < 0) currentSum = 0;
if (currentSum > maxSum) maxSum = currentSum;
}
System.out.println(maxSum);
}
}
}
Python Implementation
import sys
for line in sys.stdin:
nums = list(map(int, line.strip().split()))
if not nums:
continue
n = nums[0]
arr = nums[1:]
max_sum = 0
current_sum = 0
for num in arr:
current_sum += num
if current_sum < 0:
current_sum = 0
max_sum = max(max_sum, current_sum)
print(max_sum)
Bonus Tip: When to Use Kadane’s Algorithm?
- Competitive programming (like Codeforces, LeetCode, etc.)
- Stock market profit ranges
- Game level scoring analysis
- Sensor reading optimization
Final Words from Arrayland
The adventurer walks away with the treasure worth 20 coins, thanks to your algorithmic wisdom. With Kadane’s magic in your toolbelt, you’re now ready to solve real-world optimization puzzles — one array at a time!