“Max Circular Subarray Sum GFG Practice” Kode Jawaban

Temukan jumlah maksimum subarray melingkar

#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;
}
baba

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;
}
Nihal Parmar

Jawaban yang mirip dengan “Max Circular Subarray Sum GFG Practice”

Pertanyaan yang mirip dengan “Max Circular Subarray Sum GFG Practice”

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya