https://www.acmicpc.net/problem/2812
First i was like dafuq how do you solve this. But I sat quietly and thought for like 15 minutes until I realised i can implement a greedy pattern. When we iterate each number in that string number, if it is bigger than the previous stored numbers in our stack, we should pop them and decrement k and append our big number instead cuz we want the largest starting numbers.
I also thought i would get some leftover k if this greedy pattern is implemented like 732 and k=2. That impl will give us 732 but we need to delete 2 numbers. So if there are leftover k, we slice them from the back cuz we know the back numbers would have stored the low numbers like 1 and 2 cuz if there were high values like 9 or 8, our pattern would have caught it and would have removed those low numbers.
My initial approach was around 3000ms but i saw others was like 300ms. I looked and saw i am unnecessarily building my result string by popping each element in our stack and reversing the result string. We dont have to reverse string as stack is basically a list so we slice leftover k from the back and we can just iterate the elements with a for loop.
n, k = map(int, input().split())
number = input()
stack = [number[0]]
for i in range(1, n):
num = number[i]
while stack and stack[-1] < num and k:
stack.pop()
k -= 1
stack.append(num)
result = ""
while stack:
result += stack.pop()
result=result[::-1]
if k:
result = result[:-k]
print(result)
n, k = map(int, input().split())
number = input()
stack = [number[0]]
for i in range(1, n):
num = number[i]
while stack and stack[-1] < num and k:
stack.pop()
k -= 1
stack.append(num)
while k:
k-=1
stack.pop()
for i in stack:
print(i, end='')
n time and space?
yep
Let's analyze the time and space complexity of the provided code:
Time Complexity:
Overall, the time complexity is dominated by the linear time complexity of constructing the initial stack and printing its elements. Hence, the overall time complexity is O(n).
Space Complexity:
n, k, and num is constant.Thus, the overall space complexity is O(n) due to the space occupied by the stack.
In summary, the time complexity of the code is O(n), and the space complexity is O(n).