|
2 | 2 |
|
3 | 3 | /**
|
4 | 4 | * 1395. Count Number of Teams
|
5 |
| - * |
| 5 | + * <p> |
6 | 6 | * There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
|
7 | 7 | * You have to form a team of 3 soldiers amongst them under the following rules:
|
8 | 8 | * Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
|
9 | 9 | * A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
|
10 | 10 | * Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
|
11 |
| - * |
| 11 | + * <p> |
12 | 12 | * Example 1:
|
13 | 13 | * Input: rating = [2,5,3,4,1]
|
14 | 14 | * Output: 3
|
15 | 15 | * Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).
|
16 |
| - * |
| 16 | + * <p> |
17 | 17 | * Example 2:
|
18 | 18 | * Input: rating = [2,1,3]
|
19 | 19 | * Output: 0
|
20 | 20 | * Explanation: We can't form any team given the conditions.
|
21 |
| - * |
| 21 | + * <p> |
22 | 22 | * Example 3:
|
23 | 23 | * Input: rating = [1,2,3,4]
|
24 | 24 | * Output: 4
|
25 |
| - * |
| 25 | + * <p> |
26 | 26 | * Constraints:
|
27 | 27 | * n == rating.length
|
28 | 28 | * 1 <= n <= 200
|
29 | 29 | * 1 <= rating[i] <= 10^5
|
30 |
| - * */ |
| 30 | + */ |
31 | 31 | public class _1395 {
|
32 | 32 | public static class Solution1 {
|
33 | 33 | public int numTeams(int[] rating) {
|
34 |
| - int count = 0; |
35 |
| - //check increasing |
| 34 | + int teams = 0; |
36 | 35 | for (int i = 0; i < rating.length - 2; i++) {
|
37 | 36 | for (int j = i + 1; j < rating.length - 1; j++) {
|
38 |
| - if (rating[j] > rating[i]) { |
| 37 | + if (rating[i] < rating[j]) { |
39 | 38 | for (int k = j + 1; k < rating.length; k++) {
|
40 |
| - if (rating[k] > rating[j]) { |
41 |
| - count++; |
| 39 | + if (rating[j] < rating[k]) { |
| 40 | + teams++; |
42 | 41 | }
|
43 | 42 | }
|
44 |
| - } |
45 |
| - } |
46 |
| - } |
47 |
| - |
48 |
| - //check decreasing |
49 |
| - for (int i = 0; i < rating.length - 2; i++) { |
50 |
| - for (int j = i + 1; j < rating.length - 1; j++) { |
51 |
| - if (rating[j] < rating[i]) { |
| 43 | + } else if (rating[i] > rating[j]) { |
52 | 44 | for (int k = j + 1; k < rating.length; k++) {
|
53 |
| - if (rating[k] < rating[j]) { |
54 |
| - count++; |
| 45 | + if (rating[j] > rating[k]) { |
| 46 | + teams++; |
55 | 47 | }
|
56 | 48 | }
|
57 | 49 | }
|
58 | 50 | }
|
59 | 51 | }
|
60 |
| - return count; |
| 52 | + return teams; |
61 | 53 | }
|
62 | 54 | }
|
63 | 55 | }
|
0 commit comments