AfterAcademy Tech
•
16 Sep 2020

In which situation a 2 dimensional DP can be dropped to 1 dimension? Is there any principle or regular pattern?
Yes, the magic is the observation from the induction rule/recurrence relation!
Consider "Partition Equal Subset problem as an example", the induction rule:
nums[i - 1], then dp[i][j] = dp[i-1][j]nums[i - 1], then dp[i][j] = dp[i - 1][j - nums[i - 1]]You can see that if you point them out in the matrix, it will look something like this:

O(2*n): You can see that dp[i][j] only depends on the previous row, so you can optimize the space by only using 2 rows instead of the matrix. Let's say array1 and array2. Every time you finish updating array2, array1 has no value, you can copy array2 to array1 as the previous row of the next new row.O(n): you can also see that, the column indices of dp[i - 1][j - nums[i] and dp[i - 1][j] are <= j. The conclusion you can get is: the elements of the previous row whose column index is > j(i.e. dp[i - 1][j + 1 : n - 1]) will not affect the update of dp[i][j] since we will not touch them:
Thus if you merge array1 and array2 to a single array named array, and if you update array backward, all dependencies are not touched!

However, if you update forwards, dp[j - nums[i - 1]] is updated already, you cannot use it:

You may refer to the Dynamic Programming approach of Partition Equal Subset Sum Problem blog written here on Afteracademy.
Conclusion:
So the rule is that observe the positions of the current element and its dependencies in the matrix. Mostly if current elements depend on the elements in the previous row(most frequent case)/columns, you can optimize the space.
If you have any more approaches or you find an error/bug in the above solutions, please comment down below.
Happy Coding!
Enjoy Algorithms!
AfterAcademy Tech
This is the part 2 of the article series on hosting a website on the internet using your own laptop. In part 1 we developed the concepts of internet structure and functionings.

AfterAcademy Tech
You are given an unsorted array of integers(arr) of length n, write a program to sort it in wave form. The array elements in the resultant array must be such that arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] ... and so on. If there are multiple sorted orders in wave-form, return the one which is lexicographically smallest.

AfterAcademy Tech
Given two integer array A[] and B[] of size m and n(n <= m) respectively. We have to check whether B[] is a subset of A[] or not. An array B is a subset of another array A if each element of B is present in A. (There are no repeated elements in both the arrays)

AfterAcademy Tech
In this article, I will share the knowledge and hacks I did to convert my laptop into a server. Going forward, I must present my intentions for writing this article.
