Search
 
SCRIPT & CODE EXAMPLE
 

CPP

find maximum sum of circular subarray

#include <iostream>

using namespace std;

int kadane(int arr[], int n)
{
    int currentSum = 0;
    int maxSum = INT_MIN;
    for (int i = 0; i < n; i++)
    {
        currentSum += arr[i];
        if (currentSum < 0)
        {
            currentSum = 0;
        }
        maxSum = max(maxSum, currentSum);
    }

    return maxSum;
}
int main()
{
    //Input Array
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }

    int wrapsum, totalsum = 0;
    int nonwrapsum;

    nonwrapsum = kadane(arr, n);

    for (int i = 0; i < n; i++)
    {
        totalsum += arr[i];
        arr[i] = -arr[i];
    }
    wrapsum = totalsum + kadane(arr, n);
    cout << max(wrapsum, nonwrapsum) << endl;

    return 0;
}
Comment

max circular subarray sum gfg practice

#include <bits/stdc++.h>

using namespace std;

int kadane(int arr[], int n)
{
    int currentSum = 0;
    int maxSum = INT_MIN;
    for (int i = 0; i < n; i++)
    {
        currentSum += arr[i];
        if (currentSum < 0)
        {
            currentSum = 0;
        }
        maxSum = max(maxSum, currentSum);
    }

    return maxSum;
}
int main()
{
    //Input Array
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }

    int wrapsum, totalsum = 0;
    int nonwrapsum;

    nonwrapsum = kadane(arr, n);

    for (int i = 0; i < n; i++)
    {
        totalsum += arr[i];
        arr[i] = -arr[i];
    }
    wrapsum = totalsum + kadane(arr, n);
    cout << max(wrapsum, nonwrapsum) << endl;

    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: copy vector c++ 
Cpp :: merge sort in descending order c++ 
Cpp :: C++ Vector Operation Delete Elements 
Cpp :: stack data structure c++ 
Cpp :: phi function 
Cpp :: abs in c++ used for 
Cpp :: Array Rotate in c++ 
Cpp :: flutter text direction auto 
Cpp :: initialisation of a c++ variable 
Cpp :: file streams in c++ 
Cpp :: what destructor used for in c++ 
Cpp :: remove duplicates from sorted list solution in c++ 
Cpp :: c++ overloading by ref-qualifiers 
Cpp :: cpp serial print override always in same place 
Cpp :: print numbers after decimal point c++ 
Cpp :: Write a C++ program to Computing Mean and Median Using Arrays 
Cpp :: CPP print executable name 
Cpp :: return multiple values c++ 
Cpp :: divisor summation 
Cpp :: C++14 (gcc 8.3) sample 
Cpp :: increment integer 
Cpp :: long, long long 32 bit or 8 bit in c++ 
Cpp :: default parameter c++ a field 
Cpp :: c++ require keyword 
Cpp :: lru cache gfg 
Cpp :: delete[] cpp 
Cpp :: code::block uncomment 
Cpp :: play roblox vr on quest 2 
Cpp :: what is stdarg.h used for 
Cpp :: Explicit conversion casting 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =