Thursday, September 19, 2024
HomeWordPress DevelopmentMost prefix sum which is the same as suffix sum such that...

Most prefix sum which is the same as suffix sum such that prefix and suffix don’t overlap


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given an array arr[] of N Optimistic integers, the duty is to search out the most important prefix sum which can be the suffix sum and prefix and suffix don’t overlap.

Examples:

Enter: N = 5, arr = [1, 3, 2, 1, 4]
Output: 4
Explaination: contemplate prefix [1, 3] and suffix [4] which supplies most 
prefix sum which can be suffix sum such that prefix and suffix don’t overlap.

Enter: N = 5, arr = [1, 3, 1, 1, 4]
Output: 5

Strategy: The issue will be solved utilizing the two-pointer method.

Use two pointers from each ends of array and hold sustaining sum of prefix and suffix, hold shifting pointers until they overlap. 

Observe the steps to resolve the issue:

  • Declare and initialize two variables i = 0 and j = N – 1.
  • Declare and initialize two variables to retailer prefix and suffix sum, prefix = 0, suffix = 0.
  • Declare and initialize a variable consequence to maintain the utmost potential prefix sum, consequence = 0.
  • whereas i is lower than or equal to 
    • If prefix sum is lower than suffix sum add array aspect on the ith index to prefix sum and increment worth of i.
    • Else add array aspect on the jth index to suffix sum and decrement worth of j.
    • If each of them are equal replace the consequence variable with prefix sum.
  • Print worth of the consequence.

Under is the implementation of the above strategy.

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

int maxPrefixSum(int N, int* arr)

{

    

    

    int i = 0, j = N - 1;

  

    

    int prefixSum = 0, suffixSum = 0;

  

    

    

    int consequence = 0;

  

    

    

    whereas (i <= j) {

  

        

        

        

        if (prefixSum < suffixSum) {

            prefixSum += arr[i];

            i++;

        }

  

        

        

        

        else {

            suffixSum += arr[j];

            j--;

        }

  

        

        

        if (prefixSum == suffixSum)

            consequence = prefixSum;

    }

  

    return consequence;

}

  

int predominant()

{

    int arr[] = { 1, 3, 1, 1, 4 };

    int N = sizeof(arr) / sizeof(arr[0]);

  

    

    cout << maxPrefixSum(N, arr);

    return 0;

}

Time Complexity: O(N)
Auxiliary Area: O(1)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments