Greedy algorithm
Task
1. ν° μ λ§λ€κΈ° in Programmers (Level 2)
π Problem
https://programmers.co.kr/learn/courses/30/lessons/42883
π The point
- Compare the size of numbers and save the result to Stack -> so, itβs quite fast because of stack
π Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Stack;
class Solution {
public String solution(String number, int k) {
char[] result = new char[number.length() - k];
Stack<Character> stack = new Stack<>();
for (int i = 0; i < number.length(); i++) {
char now = number.charAt(i);
// make stack empty
// important condition : stack.peek() < now
// = if (the top of stack < now) delete top
while (!stack.isEmpty() && stack.peek() < now && k > 0) {
stack.pop();
k--;
// System.out.println("k : " + k);
}
stack.push(now);
// System.out.println("now : " + now);
// System.out.println("stack : " + stack);
// System.out.println();
}
// get the data in the order
for (int i = 0; i < result.length; i++)
result[i] = stack.get(i);
// make char array to string
return new String(result);
}
}
/**
[Logic]
- greedy algorithm : choose the best answer at each moment
- compare the numbers
**/
The source : https://wpioneer.tistory.com/110
There are so many genius in the world,,,, Iβll study all ways how they solve the problem.
Comments powered by Disqus.