|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | +#include <limits.h> |
| 5 | + |
| 6 | +void print_usage() { |
| 7 | + printf("Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"\n"); |
| 8 | +} |
| 9 | + |
| 10 | +int max_subarray_sum(int* arr, int n) { |
| 11 | + int max_so_far = INT_MIN; |
| 12 | + int max_ending_here = 0; |
| 13 | + |
| 14 | + for (int i = 0; i < n; i++) { |
| 15 | + max_ending_here += arr[i]; |
| 16 | + |
| 17 | + if (max_so_far < max_ending_here) { |
| 18 | + max_so_far = max_ending_here; |
| 19 | + } |
| 20 | + |
| 21 | + if (max_ending_here < 0) { |
| 22 | + max_ending_here = 0; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + return max_so_far; |
| 27 | +} |
| 28 | + |
| 29 | +int main(int argc, char* argv[]) { |
| 30 | + if (argc < 2) { |
| 31 | + print_usage(); |
| 32 | + return 1; |
| 33 | + } |
| 34 | + |
| 35 | + // Check if input is empty |
| 36 | + if (strlen(argv[1]) == 0) { |
| 37 | + print_usage(); |
| 38 | + return 1; |
| 39 | + } |
| 40 | + |
| 41 | + // Parse input string |
| 42 | + char* token; |
| 43 | + int arr[100]; // Assuming a maximum of 100 integers |
| 44 | + int count = 0; |
| 45 | + |
| 46 | + token = strtok(argv[1], ","); |
| 47 | + while (token != NULL) { |
| 48 | + arr[count++] = atoi(token); |
| 49 | + token = strtok(NULL, ","); |
| 50 | + } |
| 51 | + |
| 52 | + // If less than two integers were provided |
| 53 | + if (count == 1) { |
| 54 | + printf("%d\n", arr[0]); |
| 55 | + return 0; |
| 56 | + } else if (count < 2) { |
| 57 | + print_usage(); |
| 58 | + return 1; |
| 59 | + } |
| 60 | + |
| 61 | + // Calculate maximum subarray sum |
| 62 | + int result = max_subarray_sum(arr, count); |
| 63 | + |
| 64 | + printf("%d\n", result); |
| 65 | + |
| 66 | + return 0; |
| 67 | +} |
0 commit comments