Question Name:Max sum in sub-arrays

#include <iostream> 
using namespace std; 
  
int maxSum(int arr[], int n, int k) 
{ 
    if (n < k) 
    { 
       cout << "Invalid"; 
       return -1; 
    } 
  
    int res = 0; 
    for (int i=0; i<k; i++) 
       res += arr[i]; 
  

    int curr_sum = res; 
    for (int i=k; i<n; i++) 
    { 
       curr_sum += arr[i] - arr[i-k]; 
       res = max(res, curr_sum); 
    } 
  
    return res; 
} 
  
// Driver code 
int main() 
{ 
    
    int k = 2; 
    int n,i,j,a ;
  cin>>a;
  for(i=0;i<a;i++) { 
    cin>>n;
    int arr[n];
    for(j=0;j<n;j++) { 
      cin>>arr[j]; } 
    cout << maxSum(arr, n, k)<<endl; }
    return 0; 
} 

Problem Description

Given an array, find maximum sum of smallest and second smallest elements chosen from all possible sub-arrays.
More formally, if we write all (nC2) sub-arrays of array of size >=2 and find the sum of smallest and second smallest, then our answer will be maximum sum among them.

Input:

The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array. The next line contains N space separated values of the array.

Output:
For each test case in a new line print an integer denoting the maximum sum of smallest and second smallest elements chosen from all possible subarrays.

Constraints:
1<=T<=100
1<=N<=100
1<=A[]<=100

  • Test Case 1

    Input (stdin)

    2
    3
    4 5 1
    5
    4 3 1 5 6
    

    Expected Output

    9
    11
  • Test Case 2

    Input (stdin)

    1
    5
    2 3 1 5 8
    

    Expected Output

    13
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO