-
-
Notifications
You must be signed in to change notification settings - Fork 342
feat-kadane's algo #222
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat-kadane's algo #222
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR implements Kadane's algorithm for finding the maximum-sum contiguous subarray in O(n) time and O(1) space. The implementation includes comprehensive edge-case handling and a circular variant.
Key Changes:
- Core
kadane()function with proper handling of empty, single-element, and all-negative arrays - Circular array variant
kadane_circular()for wrap-around maximum subarray detection - Comprehensive test suite covering edge cases and performance validation
Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated 3 comments.
siriak
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good, thanks!
Purpose: Implements Kadane’s algorithm to find the maximum-sum contiguous subarray in a numeric vector.
Time / Space: O(n) time, O(1) extra space (excluding output subarray).
Main function: kadane(arr) — returns a list: max_sum, start (1-based), end (1-based), and subarray.
Edge-case handling: correct behavior for empty arrays (returns -Inf and NA indices) and all-negative arrays (returns the largest element).
Initialization: starts with the first element so single-element and negative-only inputs are handled naturally.
Tie behavior: returns the first-occurring maximum subarray (current code favors earlier segments).
Helper utilities: print_kadane_result() for nicely formatted output of results.
Tests included: mixed signs, all-positive, all-negative, single-element, empty array, and large random array (with timing).
Variant provided: kadane_circular() — computes max subarray sum for circular/wrap-around arrays (uses total sum − min-subarray trick); indices for wrap-around are not computed in that variant by default.
Extensibility: easy to adapt to return all maximum subarrays, or to compute wrap-around start/end indices, or to track multiple occurrences.