We need to write a program that finds the maximum subarray sum using Kadane's algorithm. The instruction is simple: "Write a program that finds the maximum subarray sum using Kadane's algorithm." It doesn't specify language, input format, etc. Typically in such coding tasks, we assume we need to implement a function or program that takes an array (maybe from standard input) and outputs the maximum subarray sum. We need to use Kadane's algorithm. I'll produce a solution in Python, since it's common.
We should also consider edge cases: empty array? Possibly we assume non-empty, or handle empty by returning 0 or None. Usually Kadane's algorithm for non-empty arrays can be implemented with initializing max_ending_here = max_so_far = arr[0] and then iterate from second element. That works for negative numbers as well, but only if we consider at least one element. If array can be empty, we could return 0 or None. We'll decide.
Also note: Kadane's algorithm finds maximum sum of contiguous subarray. The standard O(n) algorithm:
Initialize:
max_ending_here = max_so_far = arr[0]
For each x in arr[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
Return max_so_far
For all-negative numbers, it returns the maximum (least negative) single element.
We can also implement the version that returns 0 if all numbers are negative, but that's a variant. The prompt says "maximum subarray sum" without qualification, so we should return the actual sum, which could be negative if all are negative. I'll stick to the classic Kadane's algorithm.
Now, we need to write a full program. Usually it reads from stdin, e.g., a list of integers, first line n maybe. But the prompt doesn't specify. To be safe, I'll write a function max_subarray_sum(arr) and also a main that reads input. Common practice in coding problems: The input could be a line of numbers separated by spaces, or first line is number of elements and second line is the array. I'll assume the input format: first line contains an integer n (size of array), second line contains n integers. Or we can just read all integers from stdin. I'll handle both: read all integers from input, if first integer could be n? Better to read all numbers; if first number is the count, we can ignore it or use it. I'll just read all ints, if there is only one number, the array is that one number. But then if input is "5\n1 2 3 -2 5", the first number is 5, which is n. We need to treat the rest as array. Usually many problems provide n and then array. So we can read first integer as n, then read n integers. That is robust. I'll implement that.
Alternatively, we could just read all ints and treat them as array, ignoring count. But then if the input includes n, we would include it as element, which is wrong. So better to parse properly.
I'll write:
import sys
def kadane(arr):
if not arr:
return 0 # or None, but 0 is common for empty
max_ending_here = max_so_far = arr[0]
for x in arr[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
def main():
data = sys.stdin.read().strip().split()
if not data:
return
# If first token is integer n, and we have exactly n+1 tokens?
# But sometimes input may not have n, just the array. So we can try to detect:
# Usually if the problem includes n, the number of tokens after first is exactly n.
# We can check: if len(data) > 1 and int(data[0]) == len(data)-1, then assume first is n.
# But that may fail if array length equals first element. So better to follow common pattern:
# Many coding platforms provide first line as n. I'll assume first integer is n, then read next n ints.
# If there are more or less, maybe it's just array. We'll just treat all ints as array.
# Let's be simple: treat all ints as array.
# But then if n is given, it's part of array. That might not be intended.
# However, the prompt didn't specify input format, so we can just define the function.
# I'll instead provide two options: if first number is n and the total numbers match n+1, use that.
# else treat all numbers as array.
# Actually, typical solution for such prompt: They want the function, not full I/O.
# So I'll output just the function and a simple driver that reads from stdin with optional n.
code
# I'll write: read all ints into list nums. If the first integer can be the size,
# we'll check if the rest count matches it, then slice.
ints = list(map(int, data))
if len(ints) >= 2 and ints[0] == len(ints) - 1:
arr = ints[1:]
else:
arr = ints
result = kadane(arr)
print(result)
if name == "main":
main()
But that's a bit messy. Simpler: We'll just read all ints and treat as array. But we can note in comments. Many judges provide n and then array. I'll implement a standard approach: read first integer n, then read n integers from the next line or lines. That's common. Let's do that.
Read first line as n. Then read the rest of the numbers until we have n numbers. But input could be in multiple lines. We'll read all numbers after first token. Implementation: read all tokens, convert to ints, if first token is n, then the array is the next n tokens. But if there are more tokens after n? It shouldn't. So we'll just take exactly n numbers. We'll assert that there are at least n numbers after the first. So:
tokens = sys.stdin.read().split()
if not tokens:
return
n = int(tokens[0])
if len(tokens) - 1 < n:
# insufficient numbers, maybe n not given? fallback to all tokens as array
arr = list(map(int, tokens))
else:
arr = list(map(int, tokens[1:1+n]))
But again, if n is not intended, this fails. However, typical problems on platforms like LeetCode, Codeforces, etc., specify input format. Since not specified, I'll assume the input is just the array of numbers (maybe in one line). I'd rather provide the function and then a simple demonstration. The prompt likely expects the algorithm implementation, not necessarily the full I/O. In many "write a program" tasks, they want a complete runnable program that reads input and prints output. I'll provide a clean solution.
I'll write in Python:
def max_subarray_sum(arr):
if not arr:
return 0
max_ending_here = max_so_far = arr[0]
for num in arr[1:]:
max_ending_here = max(num, max_ending_here + num)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
def main():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
# Assume all numbers are the array
arr = list(map(int, data))
result = max_subarray_sum(arr)
print(result)
if name == "main":
main()
This is simple and works for any list of numbers.
We can also handle the case where the first number is n: e.g., input "5\n1 2 3 -2 5" -> arr = [5,1,2,3,-2,5] which would give wrong answer because 5 is included. But maybe the problem expects that we ignore n. But I think it's safer to assume the input is just the array. In many educational contexts, they say "write a program that reads an array and outputs the maximum subarray sum", they may not include n. Actually, if they give an array, they often give numbers separated by spaces. So our approach is fine.
Alternatively, we can check if the first token is a number and if the total tokens equals that number+1, then skip first token. But not necessary.
Given the instruction is simply to "Write a program that finds the maximum subarray sum using Kadane's algorithm", I'll provide a clear, concise program with explanation.
Also note: we can implement a version that returns 0 for empty array, but that's fine.
I'll produce final answer with code and brief comments.
I'll include the algorithm explanation in comments.
Thus final output.
python
import sys
def max_subarray_sum(arr):
"""
Kadane's algorithm to find the maximum sum of a contiguous subarray.
Works for arrays containing both positive and negative numbers.
For an empty array, returns 0.
"""
if not arr:
return 0
# Initialize with the first element
max_ending_here = max_so_far = arr[0]
for x in arr[1:]:
# Maximum sum ending at the current position
max_ending_here = max(x, max_ending_here + x)
# Update the overall maximum sum found so far
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
def main():
# Read all whitespace‑separated tokens from standard input
data = sys.stdin.read().strip().split()
if not data:
return
# Convert tokens to integers; treat all of them as the array
arr = list(map(int, data))
result = max_subarray_sum(arr)
print(result)
if __name__ == "__main__":
main()