Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calculate optimality of based on optimal substructure and overlapping subproblems #11

Open
sanjarcode opened this issue Apr 25, 2022 · 2 comments
Assignees

Comments

@sanjarcode
Copy link
Member

sanjarcode commented Apr 25, 2022

Consider this problem to understand Trapping Water - LeetCode

Understanding the problem

Suppose we start from the left and continue, we would stop at a height >= where we started, 
and then calculate the water = left * (k - j - 1) - sum(blocks in the way).

Now, apply the same logic to the largest and 2nd largest heights. Basically, we cut the maximum height to be 
the 2nd maximum height for each case (of selection of region). 
We will basically after finding water between them, 
the part on the left and right are completely independent. 
So we do have optimal substructure. 
But we don't have overlapping subproblems. So this can be done by divide and conquer.

trap(i, j) = trap(i, a) + water(a...b) + trap(b, j) where a, b are first and second maximas (in any order). 
Trap will return a number.

Also, we can reuse the walls of a region for outer regions.
*/

/*
Approach 1 - simple recursion is optimal? because we have no overlapping subproblems, so nothing to store. 
And recursion is a must because input selection is variable for each case.

As we are doing everything optimally, this is optimal? Is it?

By the way, this gave TLE error on LeetCode.

@sanjarcode sanjarcode self-assigned this Apr 25, 2022
@sanjarcode
Copy link
Member Author

sanjarcode commented Apr 25, 2022

This is important. Until now, I've been OK with what the interviewer was satisfied with and didn't actually prove/calculate optimality. This is bad because 'interviews' are not the goal of Data Structures or Algorithm Design for that matter.

@sanjarcode
Copy link
Member Author

My quick and dirty way to 'estimate' optimality. For coding questions, I calculate the time complexity of my solution and make sure it is less than 108 ops/second. But, as said, it's not about winning contests, I need to prove optimality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant