Open In App

Maximum prefix sum after K reversals of a given array

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given an array arr[] of size N and a positive integer K, the task is to find the maximum prefix sum after K reversals of the given array. 

Examples:

Input: arr[] = {1, 5, 8, 9, 11, 2}, K = 1
Output: 36
Explanation: Reverse the array once. Therefore, the array becomes {2, 11, 9, 8, 5, 1}. Maximum prefix sum = 2 + 11 + 9 + 8 + 5 + 1 = 36. 

Input: arr[] = {5, 6, -4, 3, -2, -10}, K = 2
Output : 11
Explanation: Reverse the array twice. Therefore, the array becomes {5, 6, -4, 3, -2, -10}. Maximum prefix sum = 5 + 6=11. 

Naive Approach: The simplest approach is to reverse the array K times and after K reversals, find the maximum prefix sum possible by traversing the array and print the maximum sum.

 Algorithm to implement this approach:

Reverse the entire array K times using a loop.
We can implement the reversal operation by swapping the first and last elements, then the second and second-last elements, and so on, until we reach the middle of the array.
Traverse the array and calculate the prefix sum at each index.
Keep track of the maximum prefix sum seen so far.
Return the maximum prefix sum.

 Implementation

C++




#include <iostream>
#include <vector>
using namespace std;
 
int max_prefix_sum(vector<int>& arr, int K) {
    int n = arr.size();
    for (int i = 0; i < K; i++) {
        for (int j = 0; j < n/2; j++) {
            swap(arr[j], arr[n-j-1]);
        }
    }
    int max_prefix_sum = 0;
    int prefix_sum = 0;
    for (int i = 0; i < n; i++) {
        prefix_sum += arr[i];
        if (prefix_sum > max_prefix_sum) {
            max_prefix_sum = prefix_sum;
        }
    }
    return max_prefix_sum;
}
 
int main() {
    vector<int> arr = {1, 5, 8, 9, 11, 2};
    int K = 1;
    cout << max_prefix_sum(arr, K) << endl;
    return 0;
}


Java




import java.util.ArrayList;
 
public class Main {
    public static int maxPrefixSum(ArrayList<Integer> arr, int K) {
        int n = arr.size();
 
        // Reverse the first n/2 elements of the array K times
        for (int i = 0; i < K; i++) {
            for (int j = 0; j < n/2; j++) {
                int temp = arr.get(j);
                arr.set(j, arr.get(n-j-1));
                arr.set(n-j-1, temp);
            }
        }
 
        // Compute the maximum prefix sum
        int max_prefix_sum = 0;
        int prefix_sum = 0;
        for (int i = 0; i < n; i++) {
            prefix_sum += arr.get(i);
            if (prefix_sum > max_prefix_sum) {
                max_prefix_sum = prefix_sum;
            }
        }
        return max_prefix_sum;
    }
 
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<Integer>();
        arr.add(1);
        arr.add(5);
        arr.add(8);
        arr.add(9);
        arr.add(11);
        arr.add(2);
        int K = 1;
        System.out.println(maxPrefixSum(arr, K));
    }
}


Python




def max_prefix_sum(arr, K):
    n = len(arr)
    for i in range(K):
        for j in range(n//2):
            arr[j], arr[n-j-1] = arr[n-j-1], arr[j]
    max_prefix_sum = 0
    prefix_sum = 0
    for i in range(n):
        prefix_sum += arr[i]
        if prefix_sum > max_prefix_sum:
            max_prefix_sum = prefix_sum
    return max_prefix_sum
arr = [1, 5, 8, 9, 11, 2]
K = 1
print(max_prefix_sum(arr, K))


C#




using System;
using System.Collections.Generic;
 
class GFG {
    public static int MaxPrefixSum(List<int> arr, int K) {
        int n = arr.Count;
 
        // Reverse the first n/2 elements of the array K times
        for (int i = 0; i < K; i++) {
            for (int j = 0; j < n / 2; j++) {
                int temp = arr[j];
                arr[j] = arr[n - j - 1];
                arr[n - j - 1] = temp;
            }
        }
 
        // Compute the maximum prefix sum
        int maxPrefixSum = 0;
        int prefixSum = 0;
        foreach (int num in arr) {
            prefixSum += num;
            if (prefixSum > maxPrefixSum) {
                maxPrefixSum = prefixSum;
            }
        }
        return maxPrefixSum;
    }
 
    public static void Main(string[] args) {
        List<int> arr = new List<int> { 1, 5, 8, 9, 11, 2 };
        int K = 1;
        Console.WriteLine(MaxPrefixSum(arr, K));
    }
}


Javascript




function maxPrefixSum(arr, K) {
    const n = arr.length;
     
    // Reverse the first K subarrays
    for (let i = 0; i < K; i++) {
        for (let j = 0; j < Math.floor(n / 2); j++) {
            [arr[j], arr[n - j - 1]] = [arr[n - j - 1], arr[j]]; // Swap elements
        }
    }
     
    let maxPrefixSum = 0;
    let prefixSum = 0;
     
    // Calculate the maximum prefix sum
    for (let i = 0; i < n; i++) {
        prefixSum += arr[i];
        if (prefixSum > maxPrefixSum) {
            maxPrefixSum = prefixSum;
        }
    }
     
    return maxPrefixSum;
}
 
const arr = [1, 5, 8, 9, 11, 2];
const K = 1;
console.log(maxPrefixSum(arr, K));


Output

36


Time Complexity: O(N * K)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is based on the observation that if K is odd, then the array gets reversed. Otherwise, the array remains unchanged. Therefore, if K is odd, find the maximum suffix sum. Otherwise, find the maximum prefix sum. Follow the steps below to solve the problem:

  • Initialize sum as INT_MIN to store the required answer.
  • If K is odd, reverse the array arr[].
  • Initialize currSum as 0 to store the prefix sum of elements.
  • Traverse the array arr[] using the variable i and perform the following:
    • Add arr[i] to the variable currSum.
    • If the value of currSum is greater than the sum, then update the sum as currSum.
  • After the above steps, print the value of the sum as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum prefix
// sum after K reversals of the array
int maxSumAfterKReverse(int arr[],
                        int K, int N)
{
    // Stores the required sum
    int sum = INT_MIN;
 
    // If K is odd, reverse the array
    if (K & 1)
        reverse(arr, arr + N);
 
    // Store current prefix sum of array
    int currsum = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Add arr[i] to currsum
        currsum += arr[i];
 
        // Update maximum prefix sum
        // till now
        sum = max(sum, currsum);
    }
 
    // Print the answer
    cout << sum;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 5, 8, 9, 11, 2 };
    int K = 1;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maxSumAfterKReverse(arr, K, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
 
  // Function to find the maximum prefix
  // sum after K reversals of the array
  static void maxSumAfterKReverse(Integer arr[], int K, int N)
  {
     
    // Stores the required sum
    int sum = Integer.MIN_VALUE;
 
    // If K is odd, reverse the array
    if (K % 2 != 0)
      Collections.reverse(Arrays.asList(arr));
 
    // Store current prefix sum of array
    int currsum = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
    {
 
      // Add arr[i] to currsum
      currsum += arr[i];
 
      // Update maximum prefix sum
      // till now
      sum = Math.max(sum, currsum);
    }
 
    // Print the answer
    System.out.print(sum);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    Integer[] arr = { 1, 5, 8, 9, 11, 2 };
    int K = 1;
    int N = arr.length;
 
    // Function Call
    maxSumAfterKReverse(arr, K, N);
  }
}
 
// This code is contributed by Dharanendra L V.


Python3




# Python3 program for the above approach
import sys
 
# Function to find the maximum prefix
# sum after K reversals of the array
def maxSumAfterKReverse(arr, K, N) :
     
    # Stores the required sum
    sum = -sys.maxsize - 1
 
    # If K is odd, reverse the array
    if (K & 1) :
        arr.reverse()
 
    # Store current prefix sum of array
    currsum = 0
 
    # Traverse the array arr[]
    for i in range(N):
 
        # Add arr[i] to currsum
        currsum += arr[i]
 
        # Update maximum prefix sum
        # till now
        sum = max(sum, currsum)
     
    # Print the answer
    print(sum)
 
# Driver Code
arr = [ 1, 5, 8, 9, 11, 2 ]
K = 1
N = len(arr)
 
# Function Call
maxSumAfterKReverse(arr, K, N)
 
# This code is contributed by code_hunt.


C#




// C# program for the above approach
using System;
 
class GFG{
 
  // Function to find the maximum prefix
  // sum after K reversals of the array
  static void maxSumAfterKReverse(int[] arr, int K, int N)
  {
 
    // Stores the required sum
    int sum = Int32.MinValue;
 
    // If K is odd, reverse the array
    if (K % 2 != 0)
      Array.Reverse(arr);
 
    // Store current prefix sum of array
    int currsum = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
    {
 
      // Add arr[i] to currsum
      currsum += arr[i];
 
      // Update maximum prefix sum
      // till now
      sum = Math.Max(sum, currsum);
    }
 
    // Print the answer
    Console.Write(sum);
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int[] arr = { 1, 5, 8, 9, 11, 2 };
    int K = 1;
    int N = arr.Length;
 
    // Function Call
    maxSumAfterKReverse(arr, K, N);
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
 
// Javascript program for the above approach
 
  // Function to find the maximum prefix
  // sum after K reversals of the array
  function maxSumAfterKReverse(arr, K, N)
  {
      
    // Stores the required sum
    let sum = Number.MIN_VALUE;
  
    // If K is odd, reverse the array
    if (K % 2 != 0)
      arr.reverse();
  
    // Store current prefix sum of array
    let currsum = 0;
  
    // Traverse the array arr[]
    for (let i = 0; i < N; i++)
    {
  
      // Add arr[i] to currsum
      currsum += arr[i];
  
      // Update maximum prefix sum
      // till now
      sum = Math.max(sum, currsum);
    }
  
    // Print the answer
    document.write(sum);
  }
 
// Driver Code
 
      let arr = [ 1, 5, 8, 9, 11, 2 ];
    let K = 1;
    let N = arr.length;
  
    // Function Call
    maxSumAfterKReverse(arr, K, N);
  
</script>


Output

36


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



Last Updated : 11 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads