POTD_12_OCT_2024_TwoSmallestsInEverySubarray #218
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
By maximizing consecutive element sum – O(n) time and O(1) auxiliary space
An efficient solution is based on the observation that this problem reduces to finding a maximum sum of two consecutive elements in array. If (x,y) is the pair such that (x+y) is the answer, then x and y must be consecutive elements in the array.
For a subarray with 2 elements, 1st and 2nd smallest elements are those 2 elements. Now, x and y are present in some subarray such that they are the endpoints. Now, x, y must be the smallest 2 elements of that subarray. If there are other elements Z1 , Z2, ……., ZK between x and y, they are greater than or equal to x and y,
Case1 :
If there is one element z between x and y, then the smaller subarray with the elements max(x,y) and z , should be the answer, because max(x,y) + z >= x + y
Case2:
If there are more than one elements between x and y, then the subarray within x and y will have all consecutive elements (Zi + Zi+1) >= (x+y), so (x,y) pair can’t be the answer.
So, by contradictions, x and y must be consecutive elements in the array. Time Complexity: O(n), where n is the length of given array Auxiliary Space: O(1)
Description
Please include a summary of the changes and the related issue(s) this pull request addresses. Include any relevant context or background information.
Fixes: #[issue_number] (replace with the issue number, if applicable)
Use [x] to represent a checked (ticked) box.✅
Use [ ] to represent an unchecked box.❌
Type of Change
Checklist
Additional Notes
Please add any other information that is relevant to this pull request, including potential risks, alternative solutions considered, or future improvements.