Untitled

 avatar
unknown
plain_text
a month ago
1.6 kB
3
Indexable
# Kadane's Algorithm to find the maximum sum of a subarray

def max_subarray_sum(nums):
    """
    This function takes a list of integers and returns the maximum sum of a contiguous subarray.
    """
    # Initialize variables to track the current maximum and global maximum
    current_max = global_max = nums[0]
    
    for i in range(1, len(nums)):
        # Update the current maximum sum
        current_max = max(nums[i], current_max + nums[i])
        
        # Update the global maximum sum if the current maximum is larger
        global_max = max(global_max, current_max)
    
    return global_max


# Example usage
if __name__ == "__main__":
    # Instructions for the user
    print("Welcome to the Maximum Subarray Sum Calculator!")
    print("This program uses Kadane's Algorithm to find the maximum sum of a subarray in a given list of numbers.")
    print("Example input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]")
    
    # Define the input list (Modify this to test with different inputs)
    nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
    print(f"\nInput array: {nums}")
    
    # Call the function to calculate the maximum subarray sum
    result = max_subarray_sum(nums)
    
    # Output the result
    print(f"Maximum Sum of Subarray: {result}")
    
    # Instructions for modifying the input
    print("\nTo test with a different array:")
    print("1. Open this script in a text editor.")
    print("2. Replace the `nums` array with your desired input.")
    print("3. Save the file and run it again using the command: python kadane_algorithm.py")
Leave a Comment