Hello!
- User
Hello!
- Assistant
Hello! How can I assist you today?
- User
Write a program to do the following:
The maximal sum contiguous subsequence problem is very concisely expressed in http://programmingpraxis.com/2010/12/03/maximum-sum-subsequence/ : "Given a sequence of positive and negative integers, find the contiguous subsequence with the maximum sum. For instance, given the sequence 31, -41, 59, 26,-53, 58, 97, -93, -23, 84, the maximum sum subsequence is 59, 26, -53, 58, 97, which equals 187." Algorithms with complexity O(n3), O(n2), O(n log n), and O(n) are well known. Some descriptions of different algorithms: http://wordaligned.org/articles/the-maximum-subsequence-problem http://puddleofriddles.blogspot.com/2011/11/program-to-find-maximum-contiguous.html Review these references and implement the O(n) algorithm in your language, using arrays, lists, or sequences (whichever is most appropriate to your language). If you use code found on the web, cite your source. You have to upload the Sample data for testing. Submit code (programs for all the applicable algorithms of O(n3), O(n2), O(n log n), and/or O(n) to solve this problem) and the outputs.
- Assistant
Below you'll find the implementation of the O(n) algorithm in Python that solves the maximum sum contiguous subsequence problem. This implementation does not require third-party libraries and is based on the widely-known Kadane's algorithm. The algorithm operates with a concept of a running maximum sub-array sum (local_max) and the maximum sub-array sum found so far (global_max).
def max_subarray_sum(sequence): local_max = global_max = sequence[0] start = end = s = 0 for i in range(1, len(sequence)): if sequence[i] > local_max + sequence[i]: local_max = sequence[i] s = i else: local_max += sequence[i] if local_max > global_max: global_max = local_max start = s end = i return global_max, sequence[start:end+1] # Test the algorithm with the example provided sample_data = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84] max_sum, subsequence = max_subarray_sum(sample_data) print(f"The maximum sum subsequence is {subsequence}, which equals {max_sum}.")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.