![]() |
VOOZH | about |
Given two arrays A[] and B[] having lengths N and M respectively, Where A[] and B[] can contain both positive and negative elements, the task is to find the maximum sub-array sum obtained by applying the below operations till the B[] has no element left in it:
Examples:
Input: N = 4, A[] = {72, 23, -56, 80}, M = 2, B[] = {50, 10}
Output: 179
Explanation: First Operation: Get element 50 at first index from B[] and prepend it in A[] to make A[] = {50, 72, 23 -56, 80} and B[] = {10}
Second Operation: Get element 10 at last index from B[] and append it in A[] to make A[] = {50, 72, 23 -56, 80, 10}.
Now, B[] has no elements. The maximum value of sum that can be obtained by perform given operation at most K times is: 179 by subarray (50, 72, 23, -56, 80, 10).Input: N = 2, A[] = {50, -45}, M = 2, B[] = {90},
Output: 140
Approach: The problem can be solved based on the following idea:
Problem is based on Kadane's Algorithm and Greedy approach. Find maximum subarray sum in A[] using Kadane's Algorithm let's say it as Z. Now there can be three cases for the subarray with maximum sum:
- The subarray has one end at the front: In this case adding the positive elements of B[] at the front of A[] gives the maximum possible subarray sum after the operations.
- The subarray of A[] with sum Z has one end at the end of A[]: Here appending positive elements of B[] to the end of A[] will give maximum sum.
- The subarray with maximum sum lies somewhere in between: In this case the choices are to add the positive elements of B[] to the beginning (say the maximum subarray sum from start becomes P) or to the end (say the maximum subarray sum ending at end is Q). The maximum sum will then be max among Z, P and Q.
Follow the steps given below to solve the problem:
Below is the implementation of the above approach.
179
Time Complexity: O(max(N, M))
Auxiliary Space: O(1)
Another Approach:
179
Time Complexity: O(N)
Auxiliary Space: O(1)