-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswapArrays.js
More file actions
69 lines (64 loc) · 2.35 KB
/
swapArrays.js
File metadata and controls
69 lines (64 loc) · 2.35 KB
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
// It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride! There are a number of people queued up, and each person wears a sticker indicating their initial position in the queue. Initial positions increment by from at the front of the line to at the back.
//
// Any person in the queue can bribe the person directly in front of them to swap positions. If two people swap positions, they still wear the same sticker denoting their original places in line. One person can bribe at most two others. For example, if and bribes , the queue will look like this: .
//
// Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place to get the queue into its current state!
//
// Function Description
//
// Complete the function minimumBribes in the editor below. It must print an integer representing the minimum number of bribes necessary, or Too chaotic if the line configuration is not possible.
//
// minimumBribes has the following parameter(s):
//
// q: an array of integers
// Input Format
//
// The first line contains an integer , the number of test cases.
//
// Each of the next pairs of lines are as follows:
// - The first line contains an integer , the number of people in the queue
// - The second line has space-separated integers describing the final state of the queue.
//
// Constraints
//
// Subtasks
//
// For score
// For score
//
// Output Format
//
// Print an integer denoting the minimum number of bribes needed to get the queue into its final state. Print Too chaotic if the state is invalid, i.e. it requires a person to have bribed more than people.
//
// Sample Input
//
// 2
// 5
// 2 1 5 3 4
// 5
// 2 5 1 3 4
// Sample Output
//
// 3
// Too chaotic
function minimumBribes(q) {
// q is array of interger
let count = 0;
let length = q.length;
for (let i = length - 1 ; i >= 0; i--){
// looping thru array from the back i and q[i] should be the same if current value - index is greater then 3 which means moved more than 3 bribes
// print out too chatoic
if (q[i] - i > 3) { return `Too chaotic` }
if (q[i] > i + 1) {
count = count + (q[i] - (i+1))
}
else {
if (length > q[i]) {
length = q[i]
} else if (q[i] != length) {
count ++
}
}
}
return count
}