Sum of sub-arrays

0

0 votes
, Implementation, Grammar-Verified, Recruit, Basic Programming, Hiring, Ad-Hoc, Easy, Ready, Approved, Basics of Implementation
Problem

You are given two integers N, K, and an array X of N elements.

Write a program to find the sum of the lengths of the sub-arrays with K as its maximum number.

Any two sub-arrays that are considered should not overlap each other.

Find the maximum possible sum.

Note:

  1. subarray is a slice from a contiguous array (i.e., occupy consecutive positions) and inherently maintains the order of elements. For example, the subarrays of array {1, 2, 3} are {1} , {1, 2} , {1, 2, 3} , {2} , {2, 3} , and {3}.
  2. Use 1-based indexing.

Example

Assumption

  • T = 1
  • N = 3
  • K = 4
  • X = {2, 1, 3}

Approach

There is no K=4 in the array X.

Therefore, the answer is 0.

Function description

Complete the solve function provided in the editor. This function takes the following three parameters and returns the answer.

  • N: Represents an integer denoting the size of array B.
  • K: Represents an integer K.
  • X: Represents an array of integers of size N.

Input format

Note: This is the input format that you must use to provide custom input (available above the Compile and Test button).

  • The first line contains a single integer T which denotes the number of test cases. T also specifies the number of times you have to run the solve function on a different set of inputs.
  • The first line contains two space-separated integers N and K.
  • The third line contains N space-separated integers denoting the array X.

Output format

For each test case, print the answer in a new line.

Constraints

1T50
1N3×105
1X[i],K108 (X[i] denotes the ith element of the array X)
Sum of N over all test cases in a file will be at most 5×106

Code snippets (also called starter code/boilerplate code)

This question has code snippets for C, CPP, Java, and Python.

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The first line represents T=2 test cases.

Testcase 1:

Given

  • N = 5
  • K = 4
  • X = {4, 8, 5, 2, 4}

Approach

The indexes of subarray which have 4 as the maximum number are:

  1. {1}
  2. {5}
  3. {4, 5}

You cannot pick overlapping arrays. Therefore, you will only pick subarray 1 and subarray 3.

Hence, the answer is 1+2 = 3

Testcase 2:

It is explained in the Example above.

Editor Image

?