An interesting coding problem is to find the **longest chain of numbers** in an array where each number in the chain is exactly 1 larger than the one before it, and we must preserve the array order (we can only search forward, skipping elements that don't fit).
Let's understand how we search for these runs using a simple card-stacking game analogy.
Imagine you have cards spread out in a row on a table. You want to construct the longest possible sequence of cards that increase by exactly 1 (like 0 → 1 → 2 → 3 → 4).
However, you must follow a strict rule: **you can only pick cards from left to right** (no backtracking!).
- You start with the first card (e.g.
0). - You scan the table to the right looking for a card that is exactly
1. - Once you find
1, you continue scanning to the right from that spot looking for a2. - You skip unrelated cards (like
26or8) that lie in between because they don't help build the run. - After trying every card as a starting point, the longest card run wins!
Walkthrough of the Main Method Scenario
Let's trace how the program executes step-by-step from the entry point of the main method:
The program declares our unsorted numeric array:
int[] arr = {0, 1, 26, 8, 9, 2, 3, 27, 1, 0, 4};
int count = 0;
int maxCount = 0;
The loop starts at i = 0 (value 0). We look forward in the array for previous + 1:
- Index 1: Value is
1.1 - 0 = 1. Matches! Count increases to 1, previous becomes 1. - Indices 2, 3, 4: Values are 26, 8, 9. Difference is not 1. Skipped.
- Index 5: Value is
2.2 - 1 = 1. Matches! Count increases to 2, previous becomes 2. - Index 6: Value is
3.3 - 2 = 1. Matches! Count increases to 3, previous becomes 3. - Indices 7, 8, 9: Skipped.
- Index 10: Value is
4.4 - 3 = 1. Matches! Count increases to 4, previous becomes 4.
At the end of the scan, the program updates the scoreboard: maxCount = max(0, 4 + 1) = 5.
The outer loop moves to index 1 (starting at value 1), index 2 (starting at 26), and so on. None of these runs can reach a length of 5. The program prints the winning run length: **5**.
Java Implementation
Below is the complete Java code demonstrating nested scans for increasing sequences:
package io.practise.accolite;
public class TestSecondProblem {
public static void main(String[] args) {
int[] arr = {0, 1, 26, 8, 9, 2, 3, 27, 1, 0, 4};
int count = 0;
int maxCount = 0;
for (int i = 0; i < arr.length; ++i) {
int previous = arr[i];
for (int j = i + 1; j < arr.length; ++j) {
int diff = arr[j] - previous;
if (diff == 1) {
++count;
previous = arr[j];
}
}
maxCount = Integer.max(maxCount, ++count);
count = 0;
}
System.out.println(maxCount); // Outputs: 5
}
}
Conclusion
By using nested loops, we can track the progress of runs starting at every index position in our array. Keeping a maxCount variable allows us to record and update the longest run found, ensuring we get the correct output without losing our cards!