Open In App

Maximum sum of even indexed elements obtained by right shift on an even sized subarray

Last Updated : 29 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[], we need to find the maximum sum of the even indexed elements that can be obtained by performing right shift operation on any sub-array of even length by 1.

Examples: 

Input: arr[] = {5, 1, 3, 4, 5, 6} 
Output: 15 
Explanation: 
We can perform a right shift on index 2 to 5 then resulting array is: 
arr[] = {5, 1, 6, 3, 4, 5} 
Sum of elements at even indexes = 5 + 6 + 4 = 15
Input: arr[] = {7, 9, 1, 8, 3, 10, 4, 12} 
Output: 39 
Explanation: 
We can perform a right shift on index 0 to 7 then resulting array is: 
arr[] = {12, 7, 9, 1, 8, 3, 10, 4} 
Sum of elements at even indexes = 12 + 9 + 8 + 10 = 39 
 

Naive Approach: The naive approach is to right shift every possible subarray of even length by one and find the sum of elements at even index for all the array formed after every possible subarray shifts. The maximum sum in all the array is the required result.

Below is the implementation of the above approach:

C++




#include<iostream>
#include<algorithm>
using namespace std;
 
int main(){
    int arr[] = {5, 1, 3, 4, 5, 6};
    int n = sizeof(arr)/sizeof(arr[0]);
    int max_sum = 0;
    for(int i=0; i<n; i+=2){ // iterate over all even indices as starting point
        for(int j=i; j<n; j+=2){ // iterate over all even indices as ending point
            for(int k=i; k<=j; k+=2){ // right shift every even indexed element of subarray by one
                swap(arr[k], arr[k+1]);
            }
            int sum = 0;
            for(int x=0; x<n; x+=2){ // calculate sum of all even indexed elements in resulting array
                sum += arr[x];
            }
            max_sum = max(max_sum, sum); // update max_sum if current sum is greater
            for(int k=i; k<=j; k+=2){ // restore the original array by left shifting the subarray
                swap(arr[k], arr[k+1]);
            }
        }
    }
    cout<<max_sum<<endl;
    return 0;
}
// This code is contributed by rudra1807raj


Java




import java.util.*;
 
public class Main {
    public static void main(String[] args)
    {
        int[] arr = { 5, 1, 3, 4, 5, 6 };
        int n = arr.length;
        int max_sum = 0;
        // iterate over all even indices as starting point
        for (int i = 0; i < n; i += 2) {
            // iterate over all even indices as ending point
            for (int j = i; j < n; j += 2) {
                // right shift every even indexed element of
                // subarray by one
                for (int k = i; k <= j; k += 2) {
                    int temp = arr[k];
                    arr[k] = arr[k + 1];
                    arr[k + 1] = temp;
                }
                int sum = 0;
                // calculate sum of all even indexed
                // elements in resulting array
                for (int x = 0; x < n; x += 2) {
                    sum += arr[x];
                }
                // update max_sum if current sum is greater
                max_sum = Math.max(max_sum, sum);
                // restore the original array by left
                // shifting the subarray
                for (int k = i; k <= j; k += 2) {
                    int temp = arr[k];
                    arr[k] = arr[k + 1];
                    arr[k + 1] = temp;
                }
            }
        }
        System.out.println(max_sum);
    }
}
// This code is contributed by Samim Hossain Mondal.


Python




def main():
    arr = [5, 1, 3, 4, 5, 6]
    n = len(arr)
    max_sum = 0
 
    for i in range(0, n, 2):  # iterate over all even indices as starting point
        for j in range(i, n, 2):  # iterate over all even indices as ending point
            for k in range(i, j+1, 2):  # right shift every even indexed
                                        # element of subarray by one
                arr[k], arr[k+1] = arr[k+1], arr[k]
             
            sum_even = sum(arr[0::2])  # calculate sum of all even
                                       # indexed elements in resulting array
            max_sum = max(max_sum, sum_even)  # update max_sum if current sum is greater
             
            for k in range(i, j+1, 2):  # restore the original array by left shifting the subarray
                arr[k], arr[k+1] = arr[k+1], arr[k]
 
    print(max_sum)
 
if __name__ == "__main__":
    main()


C#




using System;
 
class GFG {
    public static void Main(string[] args)
    {
        int[] arr = { 5, 1, 3, 4, 5, 6 };
        int n = arr.Length;
        int max_sum = 0;
        // Iterate over all even indices as the starting
        // point
        for (int i = 0; i < n; i += 2) {
            // Iterate over all even indices as the ending
            // point
            for (int j = i; j < n; j += 2) {
                // Right shift every even indexed element of
                // the subarray by one
                for (int k = i; k <= j; k += 2) {
                    int temp = arr[k];
                    arr[k] = arr[k + 1];
                    arr[k + 1] = temp;
                }
                int sum = 0;
                // Calculate the sum of all even indexed
                // elements in the resulting array
                for (int x = 0; x < n; x += 2) {
                    sum += arr[x];
                }
                // Update max_sum if the current sum is
                // greater
                max_sum = Math.Max(max_sum, sum);
                // Restore the original array by left
                // shifting the subarray
                for (int k = i; k <= j; k += 2) {
                    int temp = arr[k];
                    arr[k] = arr[k + 1];
                    arr[k + 1] = temp;
                }
            }
        }
        Console.WriteLine(max_sum);
    }
}
// This code is contributed by Samim Hossain Mondal.


Javascript




// Nikunj Sonigara
 
function maxEvenSum(arr) {
    const n = arr.length;
    let max_sum = 0;
 
    for (let i = 0; i < n; i += 2) { // Iterate over all even indices as the starting point
        for (let j = i; j < n; j += 2) { // Iterate over all even indices as the ending point
            for (let k = i; k <= j; k += 2) { // Right shift every even indexed element of subarray by one
                [arr[k], arr[k + 1]] = [arr[k + 1], arr[k]];
            }
 
            let sum = 0;
            for (let x = 0; x < n; x += 2) { // Calculate the sum of all even indexed elements in the resulting array
                sum += arr[x];
            }
 
            max_sum = Math.max(max_sum, sum); // Update max_sum if the current sum is greater
 
            for (let k = i; k <= j; k += 2) { // Restore the original array by left shifting the subarray
                [arr[k], arr[k + 1]] = [arr[k + 1], arr[k]];
            }
        }
    }
 
    return max_sum;
}
 
const arr = [5, 1, 3, 4, 5, 6];
const result = maxEvenSum(arr);
console.log(result);


Output

15







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

Efficient Approach: To optimized the naive above approach we can observe that after performing the right shift on any even subarray by 1 the odd index value gets replaced by even index value and vice-versa. If we find the sum of element at even indexes(say sum) before shifting, then after shifting the sum gets changed by the sum of the consecutive difference between elements at even and odd index. 
For Example: 
 

arr[] = {1, 2, 3, 4} 
Sum element at even index in the above array = 1 + 3 = 4 
Right shift array by 1, we have 
arr1[] = {4, 1, 2, 3} 
Sum element at even index in the above array = 4 + 2 = 6 
therefore the sum get differ by 2 in the above two array which is equals the sum of consecutive difference in arr[] as ( (2 – 1) + (4 – 3) = 2. 
 

We will use the above concepts to solve this problem. Below are the steps:

  • Create two arrays(say arr1[] and arr2[]) such that arr1[] will store the consecutive difference of the element in the array arr[] as: 
     
{(a[1] – a[0]), (a[3] – a[2]), . . ., (a[n]-a[n-1])}
  • And arr2[] will store the consecutive difference of the element in the array arr[] as: 
     
{(a[1] – a[2]), (a[3] – a[4]), . . ., (a[n-1]-a[n])}
  • Then find the maximum subarray sum using Kadane’s Algorithm in the above two array formed.
  • Now the maximum sum is the sum of element at even indexes in the original array(arr[]) + maximum subarray sum of the two arrays arr1[] and arr2[].

Below is the implementation of the above approach:
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Kadane's Algorithm to find
// the maximum sum sub array
int kadane(vector<int> v)
{
    int maxSoFar = 0;
    int maxEndingHere = 0;
 
    // Iterate array v
    for (int i = 0; i < v.size(); i++) {
 
        maxEndingHere += v[i];
 
        // Update the maximum
        maxSoFar = max(maxEndingHere,
                    maxSoFar);
 
        // Update maxEndingHere to 0 if it
        // is less than 0
        maxEndingHere
            = max(maxEndingHere, 0);
    }
 
    // Return maximum sum
    return maxSoFar;
}
 
// Function to find the sum
// of even indexed elements
// after modification in array.
int sumOfElements(int* arr, int n)
{
    int sum = 0;
 
    // Find initial sum of
    // even indexed elements
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0)
            sum += arr[i];
    }
 
    // Create two vectors to store
    // the consecutive differences
    // of elements
    vector<int> v1;
    vector<int> v2;
 
    for (int i = 1; i < n; i += 2) {
 
        v1.push_back(arr[i]
                    - arr[i - 1]);
 
        if (i + 1 < n) {
            v2.push_back(arr[i]
                        - arr[i + 1]);
        }
    }
 
    // Find the maximum sum subarray
    int option1 = kadane(v1);
    int option2 = kadane(v2);
 
    // Add the maximum value
    // to initial sum
    int ans = sum + max(option1,
                        option2);
 
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 5, 1, 3, 4, 5, 6 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << sumOfElements(arr, N);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Kadane's Algorithm to find
// the maximum sum sub array
static int kadane(Vector<Integer> v)
{
    int maxSoFar = 0;
    int maxEndingHere = 0;
 
    // Iterate array v
    for(int i = 0; i < v.size(); i++)
    {
    maxEndingHere += v.get(i);
         
    // Update the maximum
    maxSoFar = Math.max(maxEndingHere,
                        maxSoFar);
         
    // Update maxEndingHere to 0 if it
    // is less than 0
    maxEndingHere = Math.max(maxEndingHere, 0);
    }
     
    // Return maximum sum
    return maxSoFar;
}
 
// Function to find the sum
// of even indexed elements
// after modification in array.
static int sumOfElements(int []arr, int n)
{
    int sum = 0;
 
    // Find initial sum of
    // even indexed elements
    for(int i = 0; i < n; i++)
    {
    if (i % 2 == 0)
        sum += arr[i];
    }
 
    // Create two vectors to store
    // the consecutive differences
    // of elements
    Vector<Integer> v1 = new Vector<Integer>();
    Vector<Integer> v2 = new Vector<Integer>();
 
    for(int i = 1; i < n; i += 2)
    {
    v1.add(arr[i] - arr[i - 1]);
         
    if (i + 1 < n)
    {
        v2.add(arr[i] - arr[i + 1]);
    }
    }
     
    // Find the maximum sum subarray
    int option1 = kadane(v1);
    int option2 = kadane(v2);
 
    // Add the maximum value
    // to initial sum
    int ans = sum + Math.max(option1,
                            option2);
 
    // Return the answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 5, 1, 3, 4, 5, 6 };
 
    int N = arr.length;
 
    // Function Call
    System.out.print(sumOfElements(arr, N));
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 program for the above approach
 
# Kadane's Algorithm to find
# the maximum sum sub array
def kadane(v):
 
    maxSoFar = 0;
    maxEndingHere = 0;
 
    # Iterate array v
    for i in range(len(v)):
        maxEndingHere += v[i];
 
        # Update the maximum
        maxSoFar = max(maxEndingHere,
                    maxSoFar);
 
        # Update maxEndingHere to 0
        # if it is less than 0
        maxEndingHere = max(maxEndingHere, 0);
 
    # Return maximum sum
    return maxSoFar;
 
# Function to find the sum
# of even indexed elements
# after modification in array.
def sumOfElements(arr, n):
 
    sum = 0;
 
    # Find initial sum of
    # even indexed elements
    for i in range(n):
        if (i % 2 == 0):
            sum += arr[i];
 
    # Create two vectors to store
    # the consecutive differences
    # of elements
    v1 = [];
    v2 = [];
 
    for i in range(1, n, 2):
        v1.append(arr[i] - arr[i - 1]);
 
        if (i + 1 < n):
            v2.append(arr[i] - arr[i + 1]);
 
    # Find the maximum sum subarray
    option1 = kadane(v1);
    option2 = kadane(v2);
 
    # Add the maximum value
    # to initial sum
    ans = sum + max(option1, option2);
 
    # Return the answer
    return ans;
 
# Driver Code
if __name__ == "__main__" :
 
    # Given array arr[]
    arr = [ 5, 1, 3, 4, 5, 6 ];
 
    N = len(arr);
 
    # Function call
    print(sumOfElements(arr, N));
 
# This code is contributed by AnkitRai01


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Kadane's Algorithm to find
// the maximum sum sub array
static int kadane(List<int> v)
{
    int maxSoFar = 0;
    int maxEndingHere = 0;
 
    // Iterate array v
    for(int i = 0; i < v.Count; i++)
    {
        maxEndingHere += v[i];
             
        // Update the maximum
        maxSoFar = Math.Max(maxEndingHere,
                            maxSoFar);
             
        // Update maxEndingHere to 0 if it
        // is less than 0
        maxEndingHere = Math.Max(maxEndingHere, 0);
    }
     
    // Return maximum sum
    return maxSoFar;
}
 
// Function to find the sum
// of even indexed elements
// after modification in array.
static int sumOfElements(int []arr, int n)
{
    int sum = 0;
 
    // Find initial sum of
    // even indexed elements
    for(int i = 0; i < n; i++)
    {
        if (i % 2 == 0)
            sum += arr[i];
    }
 
    // Create two vectors to store
    // the consecutive differences
    // of elements
    List<int> v1 = new List<int>();
    List<int> v2 = new List<int>();
 
    for(int i = 1; i < n; i += 2)
    {
        v1.Add(arr[i] - arr[i - 1]);
         
        if (i + 1 < n)
        {
            v2.Add(arr[i] - arr[i + 1]);
        }
    }
     
    // Find the maximum sum subarray
    int option1 = kadane(v1);
    int option2 = kadane(v2);
 
    // Add the maximum value
    // to initial sum
    int ans = sum + Math.Max(option1,
                             option2);
 
    // Return the answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 5, 1, 3, 4, 5, 6 };
 
    int N = arr.Length;
 
    // Function call
    Console.Write(sumOfElements(arr, N));
}
}
 
// This code is contributed by Amit Katiyar


Javascript




<script>
// Javascript program for the above approach
 
// Kadane's Algorithm to find
// the maximum sum sub array
function kadane(v)
{
    var maxSoFar = 0;
    var maxEndingHere = 0;
 
    // Iterate array v
    for (var i = 0; i < v.length; i++) {
 
        maxEndingHere += v[i];
 
        // Update the maximum
        maxSoFar = Math.max(maxEndingHere,maxSoFar);
 
        // Update maxEndingHere to 0 if it
        // is less than 0
        maxEndingHere = Math.max(maxEndingHere, 0);
    }
 
    // Return maximum sum
    return maxSoFar;
}
 
// Function to find the sum
// of even indexed elements
// after modification in array.
function sumOfElements(arr, n)
{
    var sum = 0;
 
    // Find initial sum of
    // even indexed elements
    for (var i = 0; i < n; i++) {
        if (i % 2 == 0)
            sum += arr[i];
    }
 
    // Create two vectors to store
    // the consecutive differences
    // of elements
    var v1 = [];
    var v2 = [];
 
    for (var i = 1; i < n; i += 2) {
 
        v1.push(arr[i] - arr[i - 1]);
 
        if (i + 1 < n) {
            v2.push(arr[i] - arr[i + 1]);
        }
    }
 
    // Find the maximum sum subarray
    var option1 = kadane(v1);
    var option2 = kadane(v2);
 
    // Add the maximum value
    // to initial sum
    var ans = sum + Math.max(option1,
                        option2);
 
    // Return the answer
    return ans;
}
 
 
var arr = [ 5, 1, 3, 4, 5, 6 ];
 
    var N = arr.length;
     
    // Function Call
    document.write(sumOfElements(arr, N));
 
// This code is contributed by SoumikMondal
</script>


Output

15






Time Complexity: O(N), since traversal on the array is required to complete all operations hence the overall time required by the algorithm is linear.
Auxiliary Space: O(N), extra vectors are used hence algorithm takes up linear space.



Similar Reads

Construct N sized Array such that every K sized Subarray has MEX value D
Given three integers N, K and D, the task is to construct an array of size N such that every subarray of size K has a MEX value of D. If there is no possible answer, output -1. MEX of an array is the first non-negative integer that is not present in the array. Examples: Input: N = 4, K = 3, D = 4Output: -1Explanation: As D exceeds K, it is impossib
5 min read
Maximize difference between odd and even indexed array elements by shift operations
Given an array arr[] of size N, the task is to maximize the absolute difference between the sum of even indexed elements and the sum of odd indexed elements by left shift or right shift of array elements any number of times. Examples: Input: arr[] = {332, 421, 215, 584, 232}Output: 658Explanation: Convert the array to {233, 421, 152, 845, 223}, Sum
9 min read
Maximum difference between sum of even and odd indexed elements of a Subarray
Given an array nums[] of size N, the task is to find the maximum difference between the sum of even and odd indexed elements of a subarray. Examples: Input: nums[] = {1, 2, 3, 4, -5}Output: 9Explanation: If we select the subarray {4, -5} the sum of even indexed elements is 4 and odd indexed elements is -5. So the difference is 9. Input: nums[] = {1
11 min read
Maximize the difference of sum of elements at even indices and odd indices by shifting an odd sized subarray to end of given Array.
Given an array arr[] of size N, the task is to maximize the difference of the sum of elements at even indices and elements at odd indices by shifting any subarray of odd length to the end of the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Initially sum of elements at even indices = 1 + 3 + 5 = 9Sum of elements at odd ind
13 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Maximize sum of product of same-indexed elements of equal length subarrays obtained from two given arrays
Given two arrays arr[] and brr[] of size N and M integers respectively, the task is to maximize the sum of the product of the same-indexed elements of two subarrays of an equal length with the selected subarray from the array brr[] being reversed. Examples: Input: arr[] = {-1, 3, -2, 4, 5}, brr[] = {4, -5}Output: 26Explanation:Subarrays selected fr
13 min read
Reverse a subarray to maximize sum of even-indexed elements of given array
Given an array arr[], the task is to maximize the sum of even-indexed elements by reversing a subarray and print the maximum sum obtained. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 5 Explanation: Sum of initial even-indexed elements = a[0] + a[2] + a[4] = 1 + 1 + 1 = 3 Reversing subarray {1, 2, 1, 2} modifies the array to {2, 1, 2, 1, 1}. He
9 min read
Print indices of array elements whose removal makes the sum of odd and even-indexed elements equal
Given an array arr[] of size N, the task is to find indices of array elements whose removal makes the sum of odd and even indexed elements equal. If no such element exists, then print -1. Examples: Input: arr[] = {4, 1, 6, 2} Output: 1 Explanation: Removing arr[1] modifies arr[] to {4, 6, 2} Sum of even-indexed array elements = arr[0] + arr[2] = 4
13 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Rearrange array such that all even-indexed elements in the Array is even
Given an array arr[], the task is to check if it is possible to rearrange the array in such a way that every even index(1-based indexing) contains an even number. If such a rearrangement is not possible, print "No". Otherwise, print "Yes" and print a possible arrangement Examples: Input: arr[] = {2, 4, 8, 3, 1} Output: Yes 3 4 8 2 1Input: arr[] = {
6 min read
Maximize sum of each element raised to power of its frequency in K sized subarray
Given an array arr[] of N elements and an integer K. The task is to find the maximum sum of elements in a subarray of size K, with each element raised to the power of its frequency in the subarray. Examples: Input: arr[] = { 2, 1, 2, 3, 3 }, N = 5, K = 3Output: 11Explanation: Required subarray of size 3 = {2, 3, 3}. The sum is 21 + 32 = 11, which i
15 min read
Check if L sized Subarray of first N numbers can have sum S with one deletion allowed
Consider an integer sequence A = {1, 2, 3, ...., N} i.e. the first N natural numbers in order and two integers, L and S. Check whether there exists a subarray of length L and sum S after removing at most one element from A. Examples: Input: N = 5, L = 3, S = 11Output: YESExplanation: We can remove 3 from A to obtain A = {1, 2, 4, 5} where {2, 4, 5}
6 min read
Maximize the sum of maximum elements of at least K-sized subarrays
Given an integer array arr[] of length N and an integer K, partition the array in some non-overlapping subarrays such that each subarray has size at least K and each element of the array should be part of a subarray. The task is to maximize the sum of maximum elements across all the subarrays. Examples: Input: N = 4 , K = 1, arr[] = {1, 2, 3, 4}Out
7 min read
Modify given array to make sum of odd and even indexed elements same
Given a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them. Examples: Input: arr[] = {1, 1, 1, 0}Output: 1 1Explanation:For the given
10 min read
Count possible removals to make absolute difference between the sum of odd and even indexed elements equal to K
Given an array arr[] consisting of N integers and an integer K, the task is to find the number of times the absolute difference between the sum of elements at odd and even indices is K after removing any one element at a time from the given array. Examples: Input: arr[] = {2, 4, 2}, K = 2Output: 2Explanation: Removing arr[0] modifies arr[] to {4, 2
15+ min read
Count ways to make sum of odd and even indexed elements equal by removing an array element
Given an array, arr[] of size N, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal. Examples: Input: arr[] = { 2, 1, 6, 4 } Output: 1 Explanation: Removing arr[1] from the array modifies arr[] to { 2, 6, 4 } such that, arr[0] + arr[2] =
15 min read
Maximize difference between sum of even and odd-indexed elements of a subsequence
Given an array arr[] consisting of N positive integers, the task is to find the maximum possible difference between the sum of even and odd-indexed elements of a subsequence from the given array. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9 } Output: 15 Explanation: Considering the subsequences { 3, 1, 5, 1, 9 } from the array Sum of eve
7 min read
Minimum swaps of same-indexed elements required to make sum of two given arrays even
Given two arrays arr1[] and arr2[] of size N, the task is to count the minimum number of swaps of same-indexed elements from both the arrays arr1[] and arr2[] required to make the sum of all elements of both the arrays even. If it is not possible, then print "-1". Examples: Input: arr1[] = {1, 4, 2, 3}, arr2[] = {2, 3, 4, 1}Output: 0Explanation: Su
9 min read
Maximize difference between sum of even and odd-indexed elements of a subsequence | Set 2
Given an array arr[] consisting of N positive integers, the task is to find the maximum value of the difference between the sum of elements at even and odd indices for any subsequence of the array. Note: The value of N is always greater than 1. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9 } Output: 15 Explanation: Considering the subsequ
11 min read
First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Generate a N size Array where MEX of every K sized Subarray is X
Given three integers N, K and X. The task is to construct an array of size N where MEX of every K sized subarray is X. Print the constructed array elements, if not possible print -1. Examples: Input: N = 4, K = 3, X = 2Output: 1 3 4 1Explanation: Subarray of size K = 3 are: {1, 3, 4} and {3, 4, 1} and MEX of both the arrays are X = 2. Input: N = 5,
6 min read
Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the number of pairs such that the chosen elements are
12 min read
Maximum count of distinct sized subarrays with given sum
Given a binary array arr[] of N integers, the task is to find the maximum count of distinct sized subarrays such that the sum of each subarray is K. Example: Input: arr[] = {0, 1, 1 , 0}, K = 2Output: 3Explanation: The subset {{0, 1, 1, 0}, {0, 1, 1}, {1, 1}} is the subset of 3 subarrays such that the sum of each subarray is 2 and the size of each
7 min read
Maximize sum of odd-indexed array elements by repeatedly selecting at most 2*M array elements from the beginning
Given an array arr[] consisting of N integers and an integer M (initially 1), the task is to find the maximum sum of array elements chosen by Player A when two players A and B plays the game optimally according to the following rules: Player A starts the game.At every chance, X number of elements can be chosen from the beginning of the array, where
15+ min read
Generate an N-length array with sum equal to twice the sum of its absolute difference with same-indexed elements of given array
Given an array arr[] of size N, the task is to construct an array brr[] of size N that satisfies the following conditions: In every pair of consecutive elements in the array brr[], one element must be divisible by the other, i.e. brr[i] must be divisible by brr[i + 1] or vice-versa.Every ith element in the array brr[] must satisfy brr[i] >= arr[
5 min read
Maximize total set bits of elements in N sized Array with sum M
Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M. Examples: Input: N = 1, M = 15Output: 4Explanation: Since N =1, 15 is the only possible solution. The binary repr
8 min read
Minimize sum of max sized Subsequence such that no two elements are adjacent
Given an array arr[] of positive numbers, the task is to find the minimum sum of a subsequence of maximum possible elements with the constraint that no two numbers in the sequence are adjacent. Examples: Input: arr[]={1, 7, 3, 2}Output: 3Explanation: Pick the subsequence {1, 2}. The sum is 3 and no two elements are adjacent. This is the least possi
6 min read
Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
Given an array arr[] of length N, the task is to find the smallest pair of indices (i, j) such that the product of elements in the subarray arr[i + 1, j - 1] is co-prime with either the product of the subarray arr[0, i] or that of the subarray arr[j, N]. If no such pair exists, the print "-1". Examples: Input: arr[] = {2, 4, 1, 3, 7}Output: (0, 2)E
12 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Queries on Left and Right Circular shift on array
Given an array arr[] of N integers. There are three types of commands: 1 x: Right Circular Shift the array x times. If an array is a[0], a[1], ...., a[n - 1], then after one right circular shift the array will become a[n - 1], a[0], a[1], ...., a[n - 2].2 y: Left Circular Shift the array y times. If an array is a[0], a[1], ...., a[n - 1], then afte
11 min read
three90RightbarBannerImg