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 :: find second largest number in array c++ 
Cpp :: raspberry pi mount external hard drive 
Cpp :: initialisation of a c++ variable 
Cpp :: c++ last element of vector 
Cpp :: bubble sort function in c++ 
Cpp :: activity selection problem 
Cpp :: kmp c++ 
Cpp :: c++ virtual function 
Cpp :: how to compile c++ code with g+ 
Cpp :: check if cin got the wrong type 
Cpp :: codeforces problem 1030A solution 
Cpp :: C++ file . 
Cpp :: prefix using stack 
Cpp :: vector keyword in c++ 
Cpp :: top array data structure questions in inteviews 
Cpp :: how to create windows warning message c++ 
Cpp :: c++ fstream read line write ,creat file program 
Cpp :: apertura file in c++ 
Cpp :: increment integer 
Cpp :: progress bar custom color c++ buider 
Cpp :: properties of loop in c++ and how it works 
Cpp :: logisch nicht 
Cpp :: comentar todas linhas de uma vez vs code 
Cpp :: what is blob in computer vision 
Cpp :: Catcoder mars rover solution in c++ 
Cpp :: how are c++ references implemented 
Cpp :: 2000pp pp play osu std 
Cpp :: c++ find unused class methods 
Cpp :: 191. Number of 1 Bits leetcode solution in c++ 
Cpp :: sinh to hop c++ 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =