From 87bc98ec2b59c074a11f71715cdd4ac5e3f7b3ad Mon Sep 17 00:00:00 2001 From: STUTI MISHRA <153292796+stutimi@users.noreply.github.com> Date: Sun, 6 Oct 2024 03:15:47 +0000 Subject: [PATCH] sm --- C++/Kadanes_Algorithm.cpp | 65 +++++++++++++-------------------------- 1 file changed, 22 insertions(+), 43 deletions(-) diff --git a/C++/Kadanes_Algorithm.cpp b/C++/Kadanes_Algorithm.cpp index ac511d8b..5b118f50 100644 --- a/C++/Kadanes_Algorithm.cpp +++ b/C++/Kadanes_Algorithm.cpp @@ -1,58 +1,37 @@ -// Github Username: amitShindeGit #include +#include +#include // For using std::max using namespace std; -class Solution{ - public: - // arr: input array - // n: size of array - //Function to find the sum of contiguous subarray with maximum sum. - long long max(long long x, long long y){ - if(x > y){ - return x; - }else{ - return y; - } - } - - long long maxSubarraySum(int arr[], int n){ - - // Your code here +class Solution { +public: + // Function to find the sum of the contiguous subarray with the maximum sum + long long maxSubarraySum(vector& arr, int n) { long long max_current = arr[0]; long long max_global = arr[0]; - - for(int i=1; i<=n-1; i++){ - max_current = max(arr[i], max_current + arr[i]); - // cout << max_current << " " << max_global << endl; - - if(max_current > max_global){ - max_global = max_current; - } + + for (int i = 1; i < n; ++i) { + max_current = max((long long)arr[i], max_current + arr[i]); + max_global = max(max_global, max_current); } - + return max_global; - } }; - -int main() -{ - int t,n; +int main() { + int t, n; - cin>>t; //input testcases - while(t--) //while testcases exist - { + cin >> t; // input test cases + while (t--) { + cin >> n; // input size of array - cin>>n; //input size of array - - int a[n]; + vector arr(n); + for (int i = 0; i < n; ++i) { + cin >> arr[i]; // inputting elements of array + } - for(int i=0;i>a[i]; //inputting elements of array - Solution ob; - - cout << ob.maxSubarraySum(a, n) << endl; + cout << ob.maxSubarraySum(arr, n) << endl; } -} \ No newline at end of file +}