diff --git a/Python/1718_Construct_the_Lexicographically_Largest_Valid_Sequence.py b/Python/1718_Construct_the_Lexicographically_Largest_Valid_Sequence.py new file mode 100644 index 00000000..bd2aced4 --- /dev/null +++ b/Python/1718_Construct_the_Lexicographically_Largest_Valid_Sequence.py @@ -0,0 +1,45 @@ +''' +making a backtracking based sol which uses all the permutations to fit a number at a pos using backtracking. +link:-https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/?envType=daily-question&envId=2025-02-16 +''' +class Solution: + def constructDistancedSequence(self, n: int) -> List[int]: + ans = [0] * (2 * n - 1) + use = set() + + def back(i): + if i == len(ans): + return True + if ans[i]: # Skip filled positions + return back(i + 1) + + for num in range(n, 0, -1): + if num in use: + continue + if num > 1 and (i + num >= len(ans) or ans[i + num]): + continue + + # Place the number + use.add(num) + ans[i] = num + if num > 1: + ans[i + num] = num + + # Recurse to next available position + if back(i + 1): + return True + + # Backtrack + use.remove(num) + ans[i] = 0 + if num > 1: + ans[i + num] = 0 + + return False + + back(0) + return ans +if __name__ == "__main__": + s= Solution() + num = int(input()) + print(s.constructDistancedSequence(num)) diff --git a/Python/furthest-building-you-can-reach.py b/Python/furthest-building-you-can-reach.py new file mode 100644 index 00000000..ddbc9ea5 --- /dev/null +++ b/Python/furthest-building-you-can-reach.py @@ -0,0 +1,27 @@ +''' +the condition was a person can use ladder or brick to climb a building but the sucessive building's height can be greater than or less than current buiiding. +no. of bricks and ladder given,ladder length can be anything i.e if next buliding in 2 units greater than and we have no bricks so we can use ladder. +so i used maxheap to know where should i use ladder so that it will not waste my resource and we can reach the farthest building. +''' +# import heapq +class Solution: + def furthestBuilding(self, heights: list[int], bricks: int, ladders: int) -> int: + heap = [] + for i in range(len(heights)-1): + diff = heights[i+1]-heights[i] + print(diff) + if diff<0: + continue + print("hello",diff) + bricks-=diff + print("b",bricks) + heapq.heappush(heap,diff) + print(heap) + if bricks<0: + if ladders==0: + return i + ladders-=1 + print("bricks",bricks,"ladder",ladders) + bricks+=heapq.heappop(heap) + + return len(heights)-1