-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24-11-24 Kadane's Algorithm.cpp
46 lines (41 loc) · 1.06 KB
/
24-11-24 Kadane's Algorithm.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
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
// Function to find the sum of contiguous subarray with maximum sum.
int maxSubarraySum(vector<int> &arr) {
// code here...
int sum = 0;
int maxi = INT_MIN;
for(int i = 0; i<arr.size();i++){
sum += arr[i];
maxi = max(maxi , sum);
sum = sum < 0 ? 0 : sum;
}
return maxi;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore(); // To discard any leftover newline characters
while (t--) // while testcases exist
{
vector<int> arr;
string input;
getline(cin, input); // Read the entire line for the array elements
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
Solution ob;
cout << ob.maxSubarraySum(arr) << endl;
}
}
// } Driver Code Ends