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++
|
Time Complexity: O(N)
Auxiliary Area: O(1)