Skip to content
Related Articles

Related Articles

Improve Article

Maximize sum by choosing a subsegment from array [l, r] and convert arr[i] to (M–arr[i]) at most once

  • Last Updated : 06 Jul, 2021

Given an array, arr[] consisting of N positive integers and a positive integer M, the task is to maximize the sum of the array after performing at most one operation. In one operation, choose a subsegment from the array [l, r] and convert arr[i] to M – arr[i] where l≤i≤r.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {2, 4, 3}, M = 5
Output: 10
Explanation: Replace numbers in the subarray from index 0 to index 0, so the new array becomes [5-2, 4, 3], so the maximum sum will be (5-2) + 4 + 3 = 10



Input: arr[] = {4, 3, 4}, M = 5
Output: 11

Naive Approach: The simplest approach to solve the problem is to apply the operation on all the subarrays of the array and find the maximum sum applying the given operation.

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

Efficient Approach: The above approach can be optimized further by using Kadane’s Algorithm. Follow the steps below to solve the problem:

  • Initialize a variable, say sum as 0 to store the sum of the array.
  • Iterate in the range [0, N-1] using the variable i and add arr[i] to the variable sum and modify the value of arr[i] as M – 2×arr[i].
  • Now apply Kadane’s algorithm to the array arr[].
  • Initialize two variables, say mx and ans as 0.
  • Iterate in the range [0, N-1] using the variable i and perform the following steps:
    • Add arr[i] to the ans.
    • If ans<0, then modify the value of ans as 0.
    • Modify the value of mx as max(mx, ans).
  • Print the value of sum + mx as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the sum after
// performing atmost one operation
int MaxSum(int arr[], int n, int M)
{
    // Variable to store the sum
    int sum = 0;
 
    // Traverse the array and modify arr[]
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        arr[i] = (M - 2 * arr[i]);
    }
 
    int ans = 0, mx = 0;
 
    // Apply Kadane's algorithm
    for (int i = 0; i < n; i++) {
        // Add a[i] to ans
        ans += arr[i];
 
        // If ans<0, modify the value
        // of ans as 0
        if (ans < 0)
            ans = 0;
 
        // Update the value of mx
        mx = max(mx, ans);
    }
 
    // Return the maximum sum
    return mx + sum;
}
 
// Driver Code
int main()
{
    // Given Input
    int arr[] = { 2, 4, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int M = 5;
 
    // Function Call
    cout << MaxSum(arr, N, M);
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
class GFG
{
   
  // Function to maximize the sum after
// performing atmost one operation
static int MaxSum(int arr[], int n, int M)
{
   
    // Variable to store the sum
    int sum = 0;
 
    // Traverse the array and modify arr[]
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        arr[i] = (M - 2 * arr[i]);
    }
 
    int ans = 0, mx = 0;
 
    // Apply Kadane's algorithm
    for (int i = 0; i < n; i++)
    {
       
        // Add a[i] to ans
        ans += arr[i];
 
        // If ans<0, modify the value
        // of ans as 0
        if (ans < 0)
            ans = 0;
 
        // Update the value of mx
        mx = Math.max(mx, ans);
    }
 
    // Return the maximum sum
    return mx + sum;
}
 
// Driver Code
    public static void main (String[] args) {
       // Given Input
    int arr[] = { 2, 4, 3 };
    int N = arr.length;
    int M = 5;
 
    // Function Call
      
        System.out.println(MaxSum(arr, N, M));
    }
}
 
// This code is contributed by potta lokesh.

Python3




# python 3 program for the above approach
 
# Function to maximize the sum after
# performing atmost one operation
def MaxSum(arr, n, M):
    # Variable to store the sum
    sum = 0
 
    # Traverse the array and modify arr[]
    for i in range(n):
        sum += arr[i]
        arr[i] = (M - 2 * arr[i])
 
    ans = 0
    mx = 0
 
    # Apply Kadane's algorithm
    for i in range(n):
       
        # Add a[i] to ans
        ans += arr[i]
 
        # If ans<0, modify the value
        # of ans as 0
        if (ans < 0):
            ans = 0
 
        # Update the value of mx
        mx = max(mx, ans)
 
    # Return the maximum sum
    return mx + sum
 
# Driver Code
if __name__ == '__main__':
   
    # Given Input
    arr = [2, 4, 3]
    N = len(arr)
    M = 5
 
    # Function Call
    print(MaxSum(arr, N, M))
     
    # This code is contributed by SURENDRA_GANGWAR.

C#




// C# program for the above approach
using System;
class GFG {
 
    // Function to maximize the sum after
    // performing atmost one operation
    static int MaxSum(int[] arr, int n, int M)
    {
 
        // Variable to store the sum
        int sum = 0;
 
        // Traverse the array and modify arr[]
        for (int i = 0; i < n; i++) {
            sum += arr[i];
            arr[i] = (M - 2 * arr[i]);
        }
 
        int ans = 0, mx = 0;
 
        // Apply Kadane's algorithm
        for (int i = 0; i < n; i++) {
 
            // Add a[i] to ans
            ans += arr[i];
 
            // If ans<0, modify the value
            // of ans as 0
            if (ans < 0)
                ans = 0;
 
            // Update the value of mx
            mx = Math.Max(mx, ans);
        }
 
        // Return the maximum sum
        return mx + sum;
    }
 
    // Driver Code
    public static void Main()
    {
        // Given Input
        int[] arr = { 2, 4, 3 };
        int N = arr.Length;
        int M = 5;
 
        // Function Call
 
        Console.WriteLine(MaxSum(arr, N, M));
    }
}
 
// This code is contributed by ukasp.

Javascript




<script>
        // JavaScript program for the above approach
 
 
        // Function to maximize the sum after
        // performing atmost one operation
        function MaxSum(arr, n, M) {
            // Variable to store the sum
            let sum = 0;
 
            // Traverse the array and modify arr[]
            for (let i = 0; i < n; i++) {
                sum += arr[i];
                arr[i] = (M - 2 * arr[i]);
            }
 
            let ans = 0, mx = 0;
 
            // Apply Kadane's algorithm
            for (let i = 0; i < n; i++) {
                // Add a[i] to ans
                ans += arr[i];
 
                // If ans<0, modify the value
                // of ans as 0
                if (ans < 0)
                    ans = 0;
 
                // Update the value of mx
                mx = Math.max(mx, ans);
            }
 
            // Return the maximum sum
            return mx + sum;
        }
 
        // Driver Code
 
        // Given Input
        let arr = [2, 4, 3];
        let N = arr.length;
        let M = 5;
 
        // Function Call
        document.write(MaxSum(arr, N, M));
 
 
    // This code is contributed by Potta Lokesh
 
    </script>
Output
10

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :