-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path06_maximum_subarray_sum.cpp
78 lines (61 loc) · 2.18 KB
/
06_maximum_subarray_sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Problem Name: Maximum Subarray Sum
You are given a one dimensional array that may contain both positive and negative integers,
find the sum of contiguous subarray of numbers which has the largest sum.
For example, if the given array is {-2, -5, 6, -2, -3, 1, 5, -6},
then the maximum subarray sum is 7.
Input Format: The first line consists of number of test cases T. Each test case consists of two lines.
The first line of each testcase contains a single integer N denoting the number of elements for the array A.
The second line of each testcase contains N space separated integers denoting the elements of the array.
Constraints: 1 <= N <= 100000
1 <= t <= 20
-100000000 <= A[i] <= 100000000
Output Format: Output a single integer denoting the maximum subarray sum for each testcase in a new line.
Sample Input: 2
4
1 2 3 4
3
-10 5 10
Sample Output: 10
15
Explanation: For the first testcase,
maximum subarray sum is generated by the entire array - 1+2+3+4 = 10
For the second testcase ,
maximum subarray sum is generated by the subarray {5,10} - 5+10 = 15
*/
#include <iostream>
using namespace std;
// Finding Maximum Subarray Sum
int maxSubarraySum(int arr[], int range){
int currentSum = 0;
int maxSum = 0;
for (int idx=0; idx<=range-1; idx++){
currentSum += arr[idx];
if(currentSum < 0){
currentSum = 0;
}
if(currentSum > maxSum){
maxSum = currentSum;
}
}
return maxSum;
}
// Drive code
int main() {
int testCase;
cout << "Total test cases: ";
cin >> testCase;
for (int idx=0; idx<=testCase-1; idx++){
int range;
cout << "Total no. of values: ";
cin >> range;
int arr[range];
cout << "Enter values: ";
for(int idx=0; idx<=range-1; idx++){
cin >> arr[idx];
}
cout <<"Max Sub Array Sum : ";
cout << maxSubarraySum(arr, range) << endl;
}
return 0;
}