|
| 1 | +//{ Driver Code Starts |
| 2 | +// Initial Template for C |
| 3 | +#include <limits.h> |
| 4 | +#include <stdio.h> |
| 5 | +#include <stdlib.h> |
| 6 | +#include <string.h> |
| 7 | + |
| 8 | + |
| 9 | +// } Driver Code Ends |
| 10 | +// User function Template for C |
| 11 | + |
| 12 | +// Function to find the maximum circular subarray sum. |
| 13 | +int max(int a, int b) { |
| 14 | + return a > b ? a : b; |
| 15 | +} |
| 16 | + |
| 17 | +int min(int a, int b) { |
| 18 | + return a < b ? a : b; |
| 19 | +} |
| 20 | + |
| 21 | +int circularSubarraySum(int arr[], int n) { |
| 22 | + int total_sum = 0, max_sum = INT_MIN, min_sum = INT_MAX; |
| 23 | + int curr_max = 0, curr_min = 0; |
| 24 | + int all_negative = 1; |
| 25 | + |
| 26 | + for (int i = 0; i < n; i++) { |
| 27 | + total_sum += arr[i]; |
| 28 | + |
| 29 | + curr_max = max(arr[i], curr_max + arr[i]); |
| 30 | + max_sum = max(max_sum, curr_max); |
| 31 | + |
| 32 | + curr_min = min(arr[i], curr_min + arr[i]); |
| 33 | + min_sum = min(min_sum, curr_min); |
| 34 | + |
| 35 | + if (arr[i] > 0) all_negative = 0; |
| 36 | + } |
| 37 | + |
| 38 | + if (all_negative) return max_sum; |
| 39 | + |
| 40 | + return max(max_sum, total_sum - min_sum); |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +//{ Driver Code Starts. |
| 46 | + |
| 47 | +int main() { |
| 48 | + char ts[1001]; |
| 49 | + fgets(ts, sizeof(ts), stdin); |
| 50 | + int t = atoi(ts); |
| 51 | + while (t--) { |
| 52 | + char *line = NULL; |
| 53 | + size_t len = 0; |
| 54 | + long read = getline(&line, &len, stdin); |
| 55 | + |
| 56 | + int *nums = (int *)malloc(1000000 * sizeof(int)); |
| 57 | + int n = 0; |
| 58 | + char *token = strtok(line, " "); |
| 59 | + while (token != NULL) { |
| 60 | + nums[n++] = atoi(token); |
| 61 | + token = strtok(NULL, " "); // Get the next token |
| 62 | + } |
| 63 | + int arr[n]; |
| 64 | + for (int i = 0; i < n; i++) { |
| 65 | + arr[i] = nums[i]; |
| 66 | + } |
| 67 | + // char ch; |
| 68 | + // scanf("%c", &ch); |
| 69 | + // getchar(); |
| 70 | + // Check if the array is sorted using the previously defined function |
| 71 | + int ans = circularSubarraySum(arr, n); |
| 72 | + printf("%d\n", ans); |
| 73 | + |
| 74 | + printf("%s\n", "~"); |
| 75 | + free(nums); // Free dynamically allocated memory for the nums array |
| 76 | + free(line); // Free dynamically allocated memory for the input line |
| 77 | + } |
| 78 | + |
| 79 | + return 0; // Return 0 to indicate successful execution |
| 80 | +} |
| 81 | +// } Driver Code Ends |
0 commit comments