A family is about to break their piggy bank to use the money for different purposes. The piggy bank here represents an array (arr[]) consisting of N coins. The family has to split the coins of piggy bank into smaller stack (sub-array) of coins such that the sum of the difference between the maximum value and the minimum value of the coins for all the stacks (sub-arrays) is maximum. Note: Each value of the array can be used only once that is only in one subarray.
5 8 1 7 9 2
Ans = 14 -> (8-1) + (9-2) [8,1] max — 8, min = 1 [7 9 2] max = 9 min = 2
which company??
Nxtwave
You can sort and do Binary Search. In the check function you can pair up the last element with the first elements and add the difference to a counter and check if you can get counter >=mid
Can u code and send it!!
If you sort, how will you maintain the subarray?
Oh seems I read the question so fast that I skipped the word subarray and kept only the word stack in mind
what are the constraints on n? it can be solve with O(n^2) dp
1<= N <=100 1<= A[i] <= 10^5
For every subarray the first and last element should be min or max
$$$[a_l,..,a_{min},.,.,a_{max},.a_r]$$$ $$$→$$$ $$$[a_l..a_{min-1}]+[a_{min}..a_{max}]+[a_{max+1}..a_r]$$$ will only increase the answer.
Every subarray should be monotonically increasing or decreasing
$$$[a_{min},..a_i,..a_{max}]$$$ $$$→$$$ $$$[a_{min},..a_{i-1}] + [a_i,..a_{max}]$$$ will increase the answer if $$$a_i < a_{min}$$$
Using these 2 facts you can speedup the bruteforce $$$O(n^2)$$$ dp to $$$O(n)$$$
Let $$$dp[i]$$$ be the maximum value obtained by partitioning the array upto the $$$i^{th}$$$ index.
At any index $$$i$$$, you can-
$$$1$$$. Start a new partition from $$$i$$$.
$$$2$$$. Include $$$arr[i]$$$ into the previous subarray.
For $$$[1.]$$$, the $$$min$$$ and $$$max$$$ of the new partition would be $$$arr[i]$$$, so $$$dp[i] = dp[i - 1]$$$
For $$$[2.]$$$, we can iterate $$$j$$$ from $$$i$$$ to $$$1$$$ (considering 1-based indexing) and
$$$dp[i] = max(dp[i], max(arr[j], arr[j+1],..., arr[i]) - min(arr[j], arr[j+1], ...arr[i]) + dp[j - 1])$$$
Doable in $$$O(n^2)$$$
Can you code and send!
This is the code for recursive DP :-
This code works in $$$O(N^2)$$$ time and $$$O(N)$$$ space.