Home [Algorithm] Greedy1
Post
Cancel

[Algorithm] Greedy1

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.

This post is licensed under CC BY 4.0 by the author.

[Algorithm] Brute-force Search 3

[Algorithm] Greedy2

Comments powered by Disqus.