Sub-arrays
1. Find maximum sum of a subarray
Brute- time: O(n^2)
go through each subarray and thus find the maximum sum
---------------------
Optimal- time: O(n)
use Kadane Algorithm
at each element either extend old subarray or start a new one.
Handles negatives as well as positives
-----------------------------------------------------------------------------------------------------------------------------
2. Find maximum sum of subarray of size K
only positives-
use sliding window of fix size K,
and move both pointers simultaneously thus simulating fix window traversing array
-----------------------------------------------------------------------------------------------------------------------------
3. Find maximum sum of distinct subarray of size K
Brute- time: O(nK) space: O(n)
Use hashing ,
after each expansion and shrinking of sub array, check if this subarray contains duplicates or not.
-----------------------------
Optimal- time: O(n) space: O(n)
instead of checking each time if subarray contains duplicates or not, we will use a distinct counter
---------------------------------------------------------------------------------------------------------------------------
4. Find length of longest subarray with sum <= K
(array has only non negatives)
we use sliding window
----------------------------------------------------------------------------------------------------------------------------
5. Find length of longest subarray with sum = K
Case-1: both positives & negatives
we use prefix sum + hashing
we use prefix sum + hashing
---------------------------------------------------------------------------------------------------------------------------
Note-
In questions of printing subarrays or subsequences, we have to have to do with brute force, no other option .
---------------------------------------------------------------------------------------------------------------------------
6. Count subarrays with sum = K
Case-1: only positives
use sliding window pattern-3
Case-2: non negatives
use below identity:
count(sum = k) = count(sum ≤ k) − count(sum ≤ k−1)
--------------------------------------------------
Case-3: both positives & negatives
use prefix sum + hashmap
Comments
Post a Comment