Leetcode Problem 1600-1699
O(N^2) Time and O(1) Space solution
- Use inbuilt accumulate function to get the sum of all the elements in the array
Priority Queue (AC)
Set
Must Read
-
[β
C++ |
Β |
Easy |
Β |
2 Approaches |
Β |
Priority Queue |
Β |
Set](https://leetcode.com/problems/minimize-deviation-in-array/discuss/1781709/C%2B%2B-oror-Easy-oror-2-Approaches-oror-Priority-Queue-oror-Set) |
Brute force(TLE)
- Try all possible combinations of numbers and find the maximum number of operations out of them.
- Time complexity: O(n^2)
- Space complexity: O(1)
Two pointer approach
- To optimize the brute force approach, we can use two pointer approach.
- sort the array.
- take one pointer at the start and one at the end.
- if the sum of the elements at both the pointers is less than k, then we need to increase the sum, so we will move the pointer at the start to the next element.
- if the sum of the elements at both the pointers is greater than k, then we need to decrease the sum, so we will move the pointer at the end to the previous element.
- if it is equal to k, then we will increase the count of operations and move both the pointers to the next and previous element respectively.
- repeat the process until both the pointers meet.
- Time complexity: O(nlogn)
- Space complexity: O(1)
Hashmap
- We can use a hashmap to store the frequency of each element.
- we will check for pair of elements whose sum is equal to k.(i.e.{nums[i], k - nums[i]})
- if we find such a pair, then we will increase the count of operations and decrease the frequency of both the elements by 1.
- if we donβt find such a pair, then we will increase the frequency of the element by 1.
- repeat the process until we reach the end of the array.
- Time complexity: O(n)
- Space complexity: O(n)
Recursion (TLE)
- Try whats the question asking.
- For every index try to jump 1 to k steps, and get maximum score.
- if we reach outside return
nums[n-1]
.
- TC: O(k^n)
- SC: O(n), Recursion stack
Memoization (TLE)
- Memoize the result by storing it in memo array of INT_MIN.
- TC: O(k*n)
- SC: O(n), Memoization array
Tabulation (TLE) π€
- TC: O(k*n)
- SC: O(n), Memoization array
Tabulation optimization with multiset
Further optimization with dequeue