The post Triple Sum appeared first on fizzbuzzer.com.

]]>Given arrays of different sizes, find the number of distinct triplets where is an element of , written as , , and , satisfying the criteria: and

For example, given and we find four distinct triplets: $latex(3,6,4), (3,6,6), (5,6,4), (5,6,6)$

**Function Description**

Complete the triplets function in the editor below. It must return the number of distinct triplets that can be formed from the given arrays.

`triplets`

has the following parameter(s):

`a`

, `b`

, `c`

: three arrays of integers.

**Input Format**

The first line contains integers , the sizes of the three arrays.

The next lines contain space-separated integers numbering respectively.

**Constraints**

**Output Format**

Print an integer representing the number of distinct triplets.

**Sample Input 0**

3 2 3 1 3 5 2 3 1 2 3

**Sample Output 0**

8

**Explanation 0**

The special triplets are .

**Solution**

public class TripleSum { static int binarySearchIndexForValueLessEqual(int[] arr, int l, int h, int searchVal) { if (l < h) { int mid = (l + h) / 2; if (searchVal < arr[mid]) { return binarySearchIndexForValueLessEqual(arr, l, mid - 1, searchVal); } int result = binarySearchIndexForValueLessEqual(arr, mid + 1, h, searchVal); if (result == -1) { return mid; } else { return result; } } else { if (arr[l] <= searchVal) { return l; } else { return -1; } } } static long triplets(int[] a, int[] b, int[] c) { int[] arr = Arrays.stream(a).sorted().distinct().toArray(); int[] brr = Arrays.stream(b).sorted().distinct().toArray(); int[] crr = Arrays.stream(c).sorted().distinct().toArray(); Map<Integer, Integer> smallerIndexA = new HashMap<>(); Map<Integer, Integer> smallerIndexC = new HashMap<>(); long count = 0; for (int i = 0; i < brr.length; i++) { int left = binarySearchIndexForValueLessEqual(arr, 0, arr.length - 1, brr[i]) + 1; smallerIndexA.put(brr[i], left); int right = binarySearchIndexForValueLessEqual(crr, 0, crr.length - 1, brr[i]) + 1; smallerIndexC.put(brr[i], right); count += ((long)left * (long)right); } return count; } public static void main(String[] args) throws IOException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in4.txt")); Scanner scanner = new Scanner(System.in); String[] lenaLenbLenc = scanner.nextLine().split(" "); int lena = Integer.parseInt(lenaLenbLenc[0]); int lenb = Integer.parseInt(lenaLenbLenc[1]); int lenc = Integer.parseInt(lenaLenbLenc[2]); int[] arra = new int[lena]; String[] arraItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < lena; i++) { int arraItem = Integer.parseInt(arraItems[i]); arra[i] = arraItem; } int[] arrb = new int[lenb]; String[] arrbItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < lenb; i++) { int arrbItem = Integer.parseInt(arrbItems[i]); arrb[i] = arrbItem; } int[] arrc = new int[lenc]; String[] arrcItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < lenc; i++) { int arrcItem = Integer.parseInt(arrcItems[i]); arrc[i] = arrcItem; } long ans = triplets(arra, arrb, arrc); System.out.println(ans); scanner.close(); } }

The post Triple Sum appeared first on fizzbuzzer.com.

]]>The post K-Difference appeared first on fizzbuzzer.com.

]]>In this challenge, you will be given an array of integers, each unique within the array, and an integer representing a target difference. Determine the number of pairs of elements in the array that have a difference equal to the target difference.

For example, consider the array [1, 3, 5] and a target difference 2. There are two pairs: [1,3] and [3,5], that have the target difference.

**Function Description **

Complete the function kDifference in the editor below. The function must return an integer count of the number of pairs within a having a difference of k.

kDifference has the following parameter(s):

- a[a[0],…a[n-1]]: array of integers to test
- k: the target difference

**Sample Input 0**

5 1 5 3 4 2 2

**Sample Output 0**

3

**Explanation 0**

Count the number of pairs in a = [1, 5, 3, 4, 2] whose difference is k = 2. The following three pairs meet the criterion: (1, 3), (5, 3), and (4, 2).

**Solution**

public class kDifference { public static int kDifference(int[] a, int k) { int ans = 0; Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>(); for (int i= 0; i<a.length; i++) { int n = a[i]; if (!map.containsKey(n)) { map.put(n, new HashSet<>()); } map.get(n).add(i); } for (int i= 0; i<a.length; i++) { int n = a[i]; int diff = Math.abs(n - k); if (map.containsKey(diff)) { Set<Integer> indices = map.get(diff); ans += indices.size(); if (indices.contains(i)) { ans--; } } } return ans; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in5.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } int k = scanner.nextInt(); System.out.println(kDifference(a,k)); } }

The post K-Difference appeared first on fizzbuzzer.com.

]]>The post Ice Cream Parlor appeared first on fizzbuzzer.com.

]]>Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they pool their money to buy ice cream. On any given day, the parlor offers a line of flavors. Each flavor has a cost associated with it.

Given the value of and the of each flavor for trips to the Ice Cream Parlor, help Sunny and Johnny choose two distinct flavors such that they spend their entire pool of money during each visit. ID numbers are the 1- based index number associated with a . For each trip to the parlor, print the ID numbers for the two types of ice cream that Sunny and Johnny purchase as two space-separated integers on a new line. You must print the smaller ID first and the larger ID second.

For example, there are flavors having . Together they have to spend. They would purchase flavor ID’s and for a cost of . Use based indexing for your response.

**Note:**

Two ice creams having unique IDs and may have the same cost (i.e., ).

There will always be a unique solution.

**Input Format**

The first line contains an integer, , the number of trips to the ice cream parlor.

Each of the next sets of lines is as follows:

– The first line contains .

– The second line contains an integer, , the size of the array .

– The third line contains space-separated integers denoting the .

**Output Format**

Print two space-separated integers denoting the respective indices for the two distinct flavors they choose to purchase in ascending order. Recall that each ice cream flavor has a unique ID number in the inclusive range from to .

**Sample Input**

2 4 5 1 4 5 3 2 4 4 2 2 4 3

**Sample Output**

1 4 1 2

**Explanation**

Sunny and Johnny make the following two trips to the parlor:

– The first time, they pool together dollars. There are five flavors available that day and flavors and have a total cost of .

– The second time, they pool together dollars. There are four flavors available that day and flavors and have a total cost of .

**Solution**

public class IceCreamParlor2 { // Complete the whatFlavors function below. static void whatFlavors(int[] cost, int money) { Map<Integer, Integer> value2index = new HashMap<Integer, Integer>(); for (int i=0; i<cost.length; i++) { int num = cost[i]; if (value2index.containsKey(money-num)) { int id1 = value2index.get(money-num); System.out.println(id1+" "+(i+1)); break; } else { value2index.put(num, i+1); } } } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int t = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int tItr = 0; tItr < t; tItr++) { int money = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] cost = new int[n]; String[] costItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int costItem = Integer.parseInt(costItems[i]); cost[i] = costItem; } whatFlavors(cost, money); } scanner.close(); } }

The post Ice Cream Parlor appeared first on fizzbuzzer.com.

]]>The post Strokes to paint appeared first on fizzbuzzer.com.

]]>Alex wants to paint a picture but hates taking the brush off the canvas. In one stroke, Alex can only paint the same colored cells which are joined via some edge.

Given the painting, determine the minimum number of strokes to completely paint the picture.

Take for example, the canvas with height given by h = 3 and width given by w = 5 is to be painted with picture picture=[“aabba”, “aabba”, “aaaca”], the diagram below shows the 4 strokes needed to paint the canvas.

Strokes Canvas 1 2 3 4 aabba aa bb a aabba aa bb a aaaca aaa c a

**Function Description**

Complete the function strokesRequired in the editor below. The function must return an integer, the minimum number of strokes required to paint the canvas.

`strokesRequired`

has the following parameter(s):

picture[picture[0],…picture[h-1]]: an array of strings where each string represents one row of the picture to be painted

**Constraints**

1 ≤ h ≤ 105

1 ≤ w ≤ 105

1 ≤ h*w ≤ 105

len(picture[i]) = w (where 0 ≤ i < h)

picture[i][j] ∈ {‘a’, ‘b’, ‘c’} (where 0 ≤ i < h and 0 ≤ j < w)

**Sample Input For Custom Testing**

3 aaaba ababa aaaca

**Sample Output**

5

**Explanation**

The ‘a’s can be painted in 2 strokes, ‘b’s in 2 strokes and ‘c’ in 1 stroke, for a total of 5.

Strokes Canvas 1 2 3 4 5 aaaba aaa b a ababa a a b b a aaaca aaa c a

**Solution**

public class StrokesToPaint { static char VISITED = 'x'; public static void print(char[][] painting) { int rows = painting.length; int cols = painting[0].length; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { System.out.print(painting[r][c]); } System.out.println(); } System.out.println("------------------------------------"); } public static boolean isValid(int i, int j, char[][] painting, char checkChar) { int rows = painting.length; int cols = painting[0].length; if (i < 0 || j < 0 || i >= rows || j >= cols || painting[i][j] != checkChar) { return false; } else { return true; } } public static void dfs(char[][] painting, int r, int c, char checkChar) { painting[r][c] = VISITED; // With Diagonals // int[] ith = {0, 1, 1, -1, 0, -1, -1, 1}; // int[] jth = {1, 0, 1, 0, -1, -1, 1, -1}; int[] ith = {0, 1, -1, 0}; int[] jth = {1, 0, 0, -1}; for (int k = 0; k < ith.length; k++) { if (isValid(r + ith[k], c + jth[k], painting, checkChar)) { dfs(painting, r + ith[k], c + jth[k], checkChar); } } } public static int strokesRequired(char[][] painting) { int rows = painting.length; int cols = painting[0].length; // Start a DFS from every non visited cell int numberOfComponents = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (painting[r][c] != VISITED) { numberOfComponents++; dfs(painting, r, c, painting[r][c]); } } } return numberOfComponents; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in11.txt")); //Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); char[][] painting = new char[n][]; for (int i = 0; i < n; i++) { String s = scanner.next(); painting[i] = s.toCharArray(); } System.out.println(strokesRequired(painting)); } }

The post Strokes to paint appeared first on fizzbuzzer.com.

]]>The post Better Compression appeared first on fizzbuzzer.com.

]]>Consider a string, S, that is a series of characters, each followed by its frequency as an integer. The string is not compressed correctly, so there may be many occurrences of the same character. A properly compressed string will consist of one instance of each character in alphabetical order followed by the total count of that character within the string.

For example, the string a3c9b2c1 has two instances where ‘c’ is followed by a count: once with 9 occurrences, and again with 1. It should be compressed to a3b2c10.

**Function Description**

Complete the function betterCompression in the editor below. The function must return the properly compressed string.

`betterCompression`

has the following parameter:

S: a string

**Constraints**

1 ≤ size of S ≤ 100000

‘a’ ≤ characters in S ≤ ‘z’

1 ≤ frequency of each character in S ≤ 1000

**Sample Input For Custom Testing**

a12b56c1

**Sample Output**

a12b56c1

**Explanation**

Nothing gets changed here since each character occurred only once and they are already in the sorted order.

**Solution**

public class BetterCompression { public static String betterCompression(String s) { char[] str = s.toCharArray(); int[] map = new int[26]; int i = 0; int n = s.length(); while (i < n) { char ch = str[i]; if (ch >= 'a' && ch <= 'z') { int start = i + 1; int end = start; while (end < n && (str[end] >= '0' && str[end] <= '9')) { end++; } int count = Integer.parseInt(s.substring(start, end)); map[ch - 'a'] += count; i = end; } else { i++; } } StringBuilder sb = new StringBuilder(); for (char ch = 'a'; ch <= 'z'; ch++) { if (map[ch - 'a'] > 0) { sb.append(ch); sb.append(map[ch - 'a']); } } return sb.toString(); } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in7.txt")); Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out7.txt")); Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); String expected = outputScanner.nextLine(); String result = betterCompression(s); if (s.equals(expected)) { System.out.println("Fail! Expected '" + expected + "' got '" + result + "'"); } else { System.out.println(result); } //System.out.println(betterCompression("a12c56a1b5")); } }

The post Better Compression appeared first on fizzbuzzer.com.

]]>The post Mud Walls appeared first on fizzbuzzer.com.

]]>A child likes to build mud walls by placing mud between sticks positioned on a number line. The gap between sticks will be referred to as a cell, and each cell will contain one segment of wall. The height of mud in a segment cannot exceed 1 unit above an adjacent stick or mud segment. Given the placement of a number of sticks and their heights, determine the maximum height segment of mud that can be built. If no mud segment can be built, return 0.

For example, there are n = 3 sticks at stickPositions = [1, 2, 4, 7] with stickHeights = [4, 5, 7, 11]. There is no space between the first two sticks, so there is no cell for mud. Between positions 2 and 4, there is one cell. Heights of the surrounding sticks are 5 and 7, so the maximum height of mud is 5 + 1 = 6. Between positions 4 and 7 there are two cells. The heights of surrounding sticks are 7 and 11. The maximum height mud segment next to the stick of height 7 is 8. The maximum height mud next to a mud segment of height 8 and a stick of height 11 is 9. Mud segment heights are 6, 8 and 9, and the maximum height is 9. In the table below, digits are in the columns of sticks and M is in the mud segments.

7 7 M7 MM7 4MM7 M4MM7 2M4MM7 12M4MM7 12M4MM7 12M4MM7 12M4MM7

**Function Description**

Complete the function maxHeight in the editor below. The function must return an integer, the maximum height mud segment that can be built.

`maxHeight`

has the following parameter(s):

stickPositions[stickPositions[0],…stickPositions[n-1]]: an array of integers

stickHeights[stickHeights[0],…stickHeights[n-1]]: an array of integers

**Constraints**

1 ≤ n ≤ 105

1 ≤ stickPositions[i] ≤ 109 (where 0 ≤ i < n)

1 ≤ stickHeights[i] ≤ 109 (where 0 ≤ i < n)

**Sample Input For Custom Testing**

3 1 3 7 3 4 3 3

**Sample Output**

5

**Explanation**

M 1M MMM 1M3MMM7 1M3MMM7 1M3MMM7

Here stickPositions = [1, 3, 7] and stickHeights = [4, 3, 3]. There can be a segment of height 4 at position 2 supported by sticks of heights 4 and 3. Between positions 3 and 7, there can be a segment of height 4 at positions 4 and 6. Between them, a segment can be built of height 5 at position 5.

**Solution**

public class MudWalls { public static int maxHeight(int[] stickPositions, int[] stickHeights) { int n = stickPositions.length; int m = stickHeights.length; int max = 0; for (int i=0; i<n-1; i++) { if (stickPositions[i]<stickPositions[i+1]-1) { // We have a gap int heightDiff = Math.abs(stickHeights[i+1] - stickHeights[i]); int gapLen = stickPositions[i+1] - stickPositions[i] - 1; int localMax = 0; if (gapLen > heightDiff) { int low = Math.max(stickHeights[i+1], stickHeights[i]) + 1; int remainingGap = gapLen - heightDiff - 1; localMax = low + remainingGap/2; } else { localMax = Math.min(stickHeights[i+1], stickHeights[i]) + gapLen; } max = Math.max(max, localMax); } } return max; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in9.txt")); //Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] stickPositions = new int[n]; for (int i = 0; i < n; i++) { stickPositions[i] = scanner.nextInt(); } n = scanner.nextInt(); int[] stickHeights = new int[n]; for (int i = 0; i < n; i++) { stickHeights[i] = scanner.nextInt(); } System.out.println(maxHeight(stickPositions, stickHeights)); } }

The post Mud Walls appeared first on fizzbuzzer.com.

]]>The post Weird Faculty appeared first on fizzbuzzer.com.

]]>This semester you are taking a course taught by a faculty member who has a weird way of grading tests. In a test, n questions will be asked, and the correctness of the answers is already determined. For the ith question, the verdict will be v[i] (where 0 ≤ i < n). If v[i] = 1, the answer is correct but if v[i] = 0, the answer is wrong.

When a test is given, you have to answer the first k questions (indices 0 to k-1) where 0 ≤ k < n, and your friend has to answer the remaining questions (indices k to n-1) on the test. At the end, results are calculated as follows:

Your results:

int Your_result = 0; for(int i=0;i<k;i++) { if(v[i]==1) Your_result++; else Your_result--; }

Your friend’s results:

int YourFriend_result = 0; for(int i=k;i<n;i++) { if(v[i]==1) YourFriend_result++; else YourFriend_result--; }

Choose the minimum k such that Your_result > YourFriend_result.

**Function Description **

Complete the function exam in the editor below. The function must return an integer that denotes the minimum number of questions you must answer to have Your_result > YourFriend_result.

`exam`

has the following parameter(s):

v[v[0],…v[n-1]]: an array of integers

**Constraints**

1 ≤ n ≤ 105

v[i] ∈ {0,1} (where 0 ≤ i < n)

**Sample Input 0**

5 1 0 0 1 0

**Sample Output 0**

0

**Explanation 0**

n = 5

v = {1, 0, 0, 1, 0}

If you answer 0 questions (k=0) then Your_result = 0 and YourFriend_result = -1 (2 correct answers & 3 wrong answers).

**Solution**

public class WeirdFaculty { public static int exam(int[] a) { int n = a.length; int[] onesUntilIndex = new int[n + 1]; for (int i = 1; i <= n; i++) { onesUntilIndex[i] = a[i - 1] == 1 ? onesUntilIndex[i - 1] + 1 : onesUntilIndex[i - 1]; } int k = 0; for (int i = 0; i <= n; i++) { int your_ones = onesUntilIndex[i]; int you_zeros = i - your_ones; int your_sum = your_ones - you_zeros; int friend_ones = onesUntilIndex[n] - your_ones; int friend_zeros = (n - i) - friend_ones; int friend_sum = friend_ones - friend_zeros; if (your_sum > friend_sum) { k = i; break; } } return k; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt")); //Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { int x = Integer.parseInt(scanner.next()); a[i] = x; } System.out.println(exam(a)); } }

The post Weird Faculty appeared first on fizzbuzzer.com.

]]>The post Longest Subarray appeared first on fizzbuzzer.com.

]]>A subarray of array a is defined as a contiguous block of a’s elements having a length that is less than or equal to the length of the array. For example, the subarrays of array a = [1, 2, 3] are [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3]. Given an integer, k = 3, the subarrays having elements that sum to a number ≤ k are [1], [2], and [1, 2]. The longest of these subarrays is [1, 2], which has a length of 2. Given an array, a, determine its longest subarray that sums to less than or equal to a given value k.

**Function Description **

Complete the function maxLength in the editor below. The function must return an integer that represents the length of the longest subarray of a that sums to a number ≤ k.

`maxLength`

has the following parameter(s):

a[a[0],…a[n-1]]: an array of integers

k: an integer

**Constraints**

1 ≤ n ≤ 105

1 ≤ a[i] ≤ 103

1 ≤ k ≤ 109

**Sample Input 0**

3 1 2 3 4

**Sample Output 0**

2

**Explanation 0**

The subarrays of [1, 2, 3] having elements that sum to a number ≤ (k = 4) are [1], [2], [3], and [1, 2]. The longest of these is [1, 2], which has a length of 2. Return 2 as the answer.

**Solution**

public class LongestSubarray { public static int maxLength(List<Integer> a, int k) { int maxLen = -1; int sum = 0; int start = 0; int end = 0; for (int i = 0; i < a.size(); i++) { sum += a.get(i); end = i; while (sum > k) { sum -= a.get(start); start++; } maxLen = Math.max(maxLen, end - start + 1); } return maxLen; } public static void main(String[] args) { System.out.println(maxLength(Arrays.asList(1,2,3), 7)); } }

The post Longest Subarray appeared first on fizzbuzzer.com.

]]>The post Maximum Difference in an Array appeared first on fizzbuzzer.com.

]]>You are given an array of integers and must compute the maximum difference between any item and any lower indexed smaller item for all the possible pairs, i.e., for a given array

`'a'`

, find the maximum value of `a[j] - a[i]`

for all `i`

, `j`

where `0 ≤ i < j < n`

and `a[i] < a[j]`

. If no item has a smaller item with a lower index, then return `-1`

.
For example, given an array `[1, 2, 6, 4]`

, you would first compare 2 to the elements to its left. 1 is smaller, so calculate the difference 2 – 1 = 1. 6 is bigger than 2 and 1, so calculate the differences 4 and 5. 4 is only bigger than 2 and 1, and the differences are 2 and 3. The largest difference was 6 – 1 = 5.

**Function Description **

Complete the function maxDifference in the editor below. The function must return an integer representing the maximum difference in a.

`maxDifference`

has the following parameter(s):

* a[a[0],a[1],…a[n-1]]: an array of integers

**Constraints**

1 ≤ n ≤ 2 × 105

−106 ≤ a[i] ≤ 106 ∀ i ∈ [0, n − 1]

**Sample Input 0**

7 2 3 10 2 4 8 1

**Sample Output**

8

**Explanation**

n = 7, a = [2, 3, 10, 2, 4, 8, 1]

Differences are calculated as:

3 – [2] = [1]

10 – [3, 2] = [7, 8]

4 – [2, 3, 2] = [2, 1, 2]

8 – [4, 2, 3, 2] = [4, 6, 5, 6]

The maximum is found at 10 – 2 = 8.

**Solution**

class MaxDifferenceInArray2 { public static int maxDifference(List<Integer> a) { int n = a.size(); int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = a.get(i); } int[] min = new int[n]; // min[i] min up to index i min[0] = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min[i - 1]) { min[i] = arr[i]; } else { min[i] = min[i - 1]; } } int max = Integer.MIN_VALUE; for (int i = 1; i < n; i++) { if (arr[i] > min[i - 1]) { max = Math.max(max, (a.get(i) - min[i - 1])); } } if (max == Integer.MIN_VALUE) { return -1; } else { return max; } } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt")); //Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> a = new LinkedList<>(); for (int i = 0; i < n; i++) { int x = Integer.parseInt(scanner.next()); a.add(x); } System.out.println(a); System.out.println(maxDifference(a)); } }

The post Maximum Difference in an Array appeared first on fizzbuzzer.com.

]]>The post Fun with Anagrams appeared first on fizzbuzzer.com.

]]>Two strings are anagrams if they are permutations of each other. For example, “aaagmnrs” is an anagram of “anagrams”. Given an array of strings, remove each string that is an anagram of an earlier string, then return the remaining array in sorted order.

For example, given the strings `s = ['code', 'doce', 'ecod', 'framer', 'frame']`

, the strings `'doce'`

and `'ecod'`

are both anagrams of `'code'`

so they are removed from the list. The words `'frame'`

and `'framer'`

are not anagrams due to the extra `'r'`

in `'framer'`

, so they remain. The final list of strings in alphabetical order is `['code', 'frame', 'framer']`

.

**Function Description**

Complete the function `funWithAnagrams`

in the editor below. It must return a list of strings in alphabetical order, ascending.

funWithAnagrams has the following parameters:

`s[s[0],...s[n-1]]`

: an array of strings

**Constraints**

1 ≤ n ≤ 1000

1 ≤ |s[i]| ≤ 1000

Each string s[i] is made up of characters in the range ascii[a-z]

**Sample Input For Custom Testing**

4 code aaagmnrs anagrams doce

**Sample Output**

aaagmnrs code

**Explanation**

aaagmnrs and anagrams are anagrams, code and doce are anagrams. After sorting aaagmnrs comes first.

**Solution**

public class FunWithAnagrams { public static boolean areAnagram(String w1, String w2) { char[] chr1 = w1.toCharArray(); char[] chr2 = w2.toCharArray(); // Sorting the two arrays and checking for equality also works, but this is faster int[] count = new int[26]; for (char ch : chr1) { count[ch - 97] = count[ch - 97] + 1; } for (char ch : chr2) { count[ch - 97] = count[ch - 97] - 1; } for (int n : count) { if (n != 0) { return false; } } return true; } public static String key(String word) { char[] chrs = word.toCharArray(); Arrays.sort(chrs); return new String(chrs); } public static List<String> funWithAnagrams(List<String> s) { List<String> ans = new LinkedList<String>(); Set<String> found = new HashSet<String>(); for (int i=0; i<s.size(); i++) { String word = s.get(i); String key = key(word); if (!found.contains(key)) { ans.add(word); found.add(key); } } Collections.sort(ans); return ans; } public static void main(String[] args) throws FileNotFoundException { //List<String> a = Arrays.asList("code", "doce", "ecod", "framer", "frame"); List<String> a = Arrays.asList("code", "aaagmnrs", "anagrams", "doce"); System.out.println(funWithAnagrams(a)); } }

The post Fun with Anagrams appeared first on fizzbuzzer.com.

]]>