Type the Question

Saturday, February 16, 2019

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

No comments:

Post a Comment

Question Name:TOWER OF HANOI

#include < bits / stdc ++. h > #define lli long long using namespace std ; lli dp [ 202 ]; int main () { int t , n ; ...