|
| 1 | +package com.thealgorithms.dynamicprogramming; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | + |
| 5 | +/** |
| 6 | + * Problem: Longest Consecutive Difference Path |
| 7 | + * |
| 8 | + * Given an integer array, find the length of the longest path such that |
| 9 | + * the absolute difference between consecutive elements is exactly 1. |
| 10 | + * |
| 11 | + * Example: |
| 12 | + * Input: arr = [3, 4, 2, 1, 2, 3, 4, 5] |
| 13 | + * Output: 5 |
| 14 | + * Explanation: The longest path is [1, 2, 3, 4, 5] |
| 15 | + * |
| 16 | + * Category: Dynamic Programming with Hashing |
| 17 | + */ |
| 18 | +public class LongestConsecutiveDiffPath { |
| 19 | + |
| 20 | + /** |
| 21 | + * Function to find the longest consecutive difference path length |
| 22 | + * @param arr input integer array |
| 23 | + * @return length of longest path |
| 24 | + */ |
| 25 | + public static int longestPath(int[] arr) { |
| 26 | + HashMap<Integer, Integer> map = new HashMap<>(); |
| 27 | + int maxLength = 0; |
| 28 | + |
| 29 | + for (int num : arr) { |
| 30 | + int len1 = map.getOrDefault(num - 1, 0); |
| 31 | + int len2 = map.getOrDefault(num + 1, 0); |
| 32 | + int currentLen = Math.max(len1, len2) + 1; |
| 33 | + map.put(num, currentLen); |
| 34 | + maxLength = Math.max(maxLength, currentLen); |
| 35 | + } |
| 36 | + |
| 37 | + return maxLength; |
| 38 | + } |
| 39 | + |
| 40 | + public static void main(String[] args) { |
| 41 | + int[] arr = {3, 4, 2, 1, 2, 3, 4, 5}; |
| 42 | + System.out.println("Longest consecutive difference path length: " + longestPath(arr)); |
| 43 | + |
| 44 | + int[] arr2 = {1, 2, 3, 4, 2, 3, 4, 5, 6}; |
| 45 | + System.out.println("Longest consecutive difference path length: " + longestPath(arr2)); |
| 46 | + |
| 47 | + int[] arr3 = {10, 9, 8, 7, 6}; |
| 48 | + System.out.println("Longest consecutive difference path length: " + longestPath(arr3)); |
| 49 | + } |
| 50 | +} |
0 commit comments