|
1 | | -#include<iostream> |
| 1 | +/** |
| 2 | + * Our task is to take length of array and then the whole array as input from |
| 3 | + * the user and then calculate the maximum contiguous subarray sum for the |
| 4 | + * input array, using the kadane's algorithm. |
| 5 | + * |
| 6 | + * There can be a case that all the elements in the input array are negative. |
| 7 | + * In that case, the least value among all elements is the maximum sum with |
| 8 | + * subarray length = 1. |
| 9 | + */ |
| 10 | + |
| 11 | +#include <climits> // for INT_MIN value |
| 12 | +#include <iostream> // for IO operations |
2 | 13 | using namespace std;
|
3 | | -int main() |
| 14 | + |
| 15 | +/** |
| 16 | + * max_suarray_sum function calculates the maximum contiguous sum for the given array. |
| 17 | + */ |
| 18 | +int max_subarray_sum(int arr[], int length) |
4 | 19 | {
|
5 | | - int cs=0; |
6 | | - int ms=0; |
7 | | - int n;cin>>n; |
8 | | - int a[100]; |
9 | | - for(int i=0;i<n;i++) |
| 20 | + int current_max = INT_MIN, current_sum = 0; |
| 21 | + for (int i = 0; i < length; i++) |
10 | 22 | {
|
11 | | - cin>>a[i]; |
12 | | - |
| 23 | + current_sum = current_sum + arr[i]; |
| 24 | + if (current_max < current_sum) |
| 25 | + { |
| 26 | + current_max = current_sum; |
| 27 | + } |
| 28 | + |
| 29 | + if (current_sum < 0) |
| 30 | + { |
| 31 | + current_sum = 0; |
| 32 | + } |
13 | 33 | }
|
14 | | - for(int i=0;i<n;i++) |
| 34 | + return current_max; |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | +* example test cases |
| 39 | +* { |
| 40 | +* arr = {1, 2, 3, 4} |
| 41 | +* maximum contiguos subarray sum = 1 +たす 2 +たす 3 +たす 4 =わ 10 |
| 42 | +* arr1 = {-1, -2, -4, -6, 7} |
| 43 | +* maximum contiguos subarray sum = 7 |
| 44 | +* arr1 = {-1, -2, -4, -6, -7} |
| 45 | +* maximum contiguos subarray sum = -1 |
| 46 | +* } |
| 47 | +*/ |
| 48 | + |
| 49 | +// main function |
| 50 | +int main() |
| 51 | +{ |
| 52 | + // code for accepting array from user starts |
| 53 | + |
| 54 | + int n; // variable for length of input array |
| 55 | + cout << "Enter length of the array: "; |
| 56 | + cin >> n; |
| 57 | + int arr[n]; // array to store the input array |
| 58 | + |
| 59 | + for (int i = 0; i < n; i++) //taking elements of the array |
15 | 60 | {
|
16 | | - cs= cs+a[i]; |
17 | | - if(cs<0) |
| 61 | + |
18 | 62 | {
|
19 | | - cs=0; |
| 63 | + cin >> arr[i]; |
20 | 64 | }
|
21 | | - ms= max(ms,cs); |
22 | 65 | }
|
23 | | - cout<<"MAXIMUM SUM IS:"<<ms<<endl; |
| 66 | + // code for accepting array from user ends |
| 67 | + int max_sum = max_subarray_sum(arr, n); // max_sum stores the maximum contiguous subarray sum |
| 68 | + cout << "Maximum contiguous sum for this array is : " << max_sum << endl; |
| 69 | + |
| 70 | + return 0; |
24 | 71 | }
|
0 commit comments