-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarryforward.java
More file actions
executable file
·84 lines (71 loc) · 1.92 KB
/
Copy pathcarryforward.java
File metadata and controls
executable file
·84 lines (71 loc) · 1.92 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public class carryforward {
public static void main(String[] args) {
String str = "ABCGAG";
int[] A = { 377, 448, 173, 307, 108 };
// specialSubSequence(str);
closestMinMax(A);
}
// Special Subsequences "AG"
static void specialSubSequence(String A) {
int n = A.length();
int count = 0;
int MOD = 10 * 1000 * 1000 + 7;
// ! Approach 1
// loop through string --> as soon as find A --> start another loop to find
// number of G
// for (int i = 0; i < n; i++) {
// char character = A.charAt(i);
// if (character == 'A') {
// for (int j = i + 1; j < n; j++) {
// char ch = A.charAt(j);
// if (ch == 'G') {
// count++;
// }
// }
// }
// }
// ! Approach 2
// single loop if found a then increase count of 'A'
// if found 'G' then increase count of ans as per 'A' count
int countA = 0;
for (int i = 0; i < n; i++) {
char character = A.charAt(i);
if (character == 'A') {
countA++;
}
if (character == 'G') {
count += countA;
count %= MOD;
}
}
System.out.println(count);
}
// Closest min-max subarray
static void closestMinMax(int[] A) {
int n = A.length;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (A[i] > max) {
max = A[i];
}
if (A[i] < min) {
min = A[i];
}
}
int minIndex = 0;
int maxIndex = 0;
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (A[i] == min) {
minIndex = i;
}
if (A[i] == max) {
maxIndex = i;
int distance = maxIndex - minIndex + 1;
ans = Math.min(ans, distance);
}
}
System.out.println(ans);
}
}