Home [Algorithm] Queue3
Post
Cancel

[Algorithm] Queue3

Queue

Explain


Task

Previous task 1 Previous task 2

๐Ÿ“Œ 3. ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ in Programmers (Level 2)

โญ๏ธ The point

  • Used while loop and break

๐Ÿ“Œ 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Queue;
import java.util.LinkedList;
    
class Solution {
    
    private Queue<Integer> queue;
    
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        
        int time = 0;
        int sumOfWeight = 0;
        queue = new LinkedList<>(); 
        
        for (int i = 0; i < truck_weights.length; i++) {
            int truck = truck_weights[i];
            
            while (true) {
                
                // case1. just add truck, don't need to consider sum of weights
                if (queue.isEmpty()) {
                    queue.add(truck);
                    sumOfWeight += truck;
                    time++;
                    break; // already added truck, so go out whlie loop
                }
                // case2. add truck and need to consider sum of weights
                else if (!queue.isEmpty() && queue.size() == bridge_length) {
                    int arrived = queue.poll();
                    sumOfWeight -= arrived;
                }
                // case3. 
                else if (!queue.isEmpty()) {
                    
                    // Let's consider sum of weights
                    // case2-1. 
                    if (sumOfWeight + truck > weight) {
                        queue.add(0); // add nothing
                        time++;
                    }
                    // case2-2.
                    else {
                        queue.add(truck);
                        sumOfWeight += truck;
                        time++;
                        break;
                    }
                }
            }
        }
        // have to + bridge_length because the remained trucks also must be arrived
        return time + bridge_length; // important 
    }
}

/**
[Question]
- ํŠธ๋Ÿญ ์—ฌ๋Ÿฌ ๋Œ€๊ฐ€ ์ •ํ•ด์ง„ ์ˆœ์œผ๋กœ ๊ฑด๋„˜
- return ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋‹ค๋ฆฌ๋ฅผ '์ˆœ์„œ๋Œ€๋กœ ์ตœ๋‹จ ์‹œ๊ฐ„ ์•ˆ์—' ๊ฑด๋„ˆ๋ ค๋ฉด ์ตœ์†Œ ๋ช‡ ์ดˆ?

[Condition]
- ๋‹ค๋ฆฌ
    - ํŠธ๋Ÿญ์ด ์ตœ๋Œ€ bridge_length๋Œ€ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ์œผ๋ฉฐ
    - weight ์ดํ•˜๊นŒ์ง€์˜ ๋ฌด๊ฒŒ๋ฅผ ๊ฒฌ๋”œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
    - ๋‹จ, ๋‹ค๋ฆฌ์— ์™„์ „ํžˆ ์˜ค๋ฅด์ง€ ์•Š์€ ํŠธ๋Ÿญ์˜ ๋ฌด๊ฒŒ๋Š” ๋ฌด์‹œ
    
- bridge_length, weight, truck_weights : 1 ~ 10,000

[Example]
- ํŠธ๋Ÿญ 2๋Œ€ + ๋ฌด๊ฒŒ ์ด ํ•ฉ 10kg๊นŒ์ง€
- ํŠธ๋Ÿญ [7, 4, 5, 6]
-> ์ตœ์†Œ 8์ดˆ
**/

Letโ€™s keep it simple always.

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

[Algorithm] DFS vs BFS

[Algorithm] Stack

Comments powered by Disqus.