Thursday, July 6th
Today's problem was to find a minimum subarray that meets or exceeds a given target sum.
First, I tried brute force with a nested for-loop that ran in O(n^2) time. Even though I knew it would likely fail one of the lengthy test cases and exceed the time limit, coding the brute force can help reinforce understanding of the problem.
Next I thought about dynamic programming, but for 2 reasons realized this probably wasn't the right approach. For one, how the problems overlap wasn't immediately clear, and second, there are several variables required to adequately capture state - e.g. sum, index, count - and that would be too many for a medium problem, so dynamic programming was ruled out.
So that left Sliding Window. Have an outer for loop incrementing the right side of the window, and if the target sum is reached, increment the left side of the window using a while loop, subtracting values until the a sum is reached below the threshold.
Comments
Post a Comment