Max Prefix

Easy
0/40
Average time to solve is 7m
profile
Contributed by
4 upvotes
Asked in company
BNY Mellon

Problem statement

You are given an array 'A' of length 'N'. You can perform the operation defined below any number of times (Possibly 0).

Choose 'l', 'r' (1 <= 'l' <= 'r' <='N') and reverse the subarray from 'l' to 'r'.

After that, Return the maximum possible sum of the prefix of this array of length 'K'.

For Example:-
Let 'N' = 5, 'K' = 3, 'A' = [4, 2, 1, 2, 2].
We can reverse the subarray from index 3 to 4 (1-based indexing).
Array becomes [4, 2, 2, 1, 2].
Our answer is 8.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:-
First-line contains an integer 'T', which denotes the number of test cases.
For every test case:-
First-line contains two integers 'N' and 'K'.
Second-line contains 'N' space-separated integers, elements of array 'A'.
Output Format:-
For each test case, Return the maximum possible sum of the prefix of this array of length 'K'.
Note:-
You don’t need to print anything. Just implement the given function.
Constraints:-
1 <= 'T' <= 10
1 <= 'K' <= 'N' <= 10^5
1 <= 'A[i]' <= 10^3

The Sum of 'N' overall test cases does not exceed 10^5.
Time Limit: 1 sec
Sample Input 1:-
2
2 2 
1 3
3 2
2 2 3
Sample Output 1:-
4
5
Explanation of sample input 1:-
First test case:-
We do not need to reverse any subarray.
Our answer is 4.

Second test case:-
We can reverse the subarray from index 1 to 3 (1-based indexing).
Array becomes [3, 2, 2].
Our answer is 5.
Sample Input 2:-
2
4 3
4 3 2 1
5 5 
1 2 3 4 5
Sample Output 2:-
9
15
Hint

How can we maximize the sum of some prefixes of this array?

Approaches (1)
Sorting Approach

Approach:-

 

  • If we place greater elements at the start, then we can maximize the sum of prefixes.
  • We can perform operations in such a way:
    • Index 1 to index with the largest element.
    • Index 2 to index with the 2nd largest element.
    • And so on.
  • With this, we can sort our array in non-increasing order.
  • So we just have to find the sum of the first 'K' largest elements.
     

Algorithm:-
 

  • Create 'ans'.
  • Sort 'A' in non-increasing order.
  • Iterate using 'i' from 1 to 'K':
    • 'ans' += 'A[i]'.
  • Return 'ans' which is the required answer.
Time Complexity

O(N*log(N)), where 'N' is the length of the array 'A'.

 

We are sorting 'A' in non-increasing order and the complexity associated with this is O(N*log(N)). Hence, the overall time complexity is of the order O(N*log(N)).

Space Complexity

O(1).

 

We are using constant extra space, So the Space Complexity is O(1).

Code Solution
(100% EXP penalty)
Max Prefix
Full screen
Console