Longest Consecutive Subsequence in ABAP

Suppose we have an array of integers. We have to find the length of the longest consecutive elements sequence. So if the input is like [100, 4, 250, 1, 3, 2,101], answer will be 4, as the longest consecutive sequence is [1,2,3,4].

REPORT ZLNGCONSUB.

TYPES: BEGIN OF ty_arr,
  num TYPE i,
  END OF ty_arr.

  TYPES: BEGIN OF ty_max,
    num TYPE i,
    len TYPE i,
    END OF ty_max.

  DATA: ls_arr TYPE ty_arr,
        ls_arr2 TYPE ty_arr,
        lt_arr TYPE SORTED TABLE OF ty_arr WITH UNIQUE KEY num,
        ls_max_t TYPE ty_max,
        ls_max TYPE ty_max,
        lv_num TYPE i.

  lt_arr = VALUE #( ( num = 100 ) ( num = 3 ) ( num = 5 ) ( num = 101 ) ( num = 4 ) ( num = 2 )
                    ( num = 1 ) ( num = 98 ) ( num = 102 ) ( num = 99 ) ( num = 111 ) ( num = 9 )
                    ( num = 13 ) ( num = 14 ) ( num = 15 ) ( num = 16 ) ( num = 8 ) ( num = 17 )
                    ( num = 88 ) ( num = 80 ) ( num = 97 )
                  ).
 ls_max-num = 0.
 ls_max-len = 0.

 READ TABLE lt_arr INTO ls_arr INDEX 1.
 ls_max_t-num = ls_arr-num.
 ls_max_t-len = 1.

 CLEAR ls_arr.

 LOOP AT lt_arr INTO ls_arr.

   IF ls_max_t-len = 0.

       ls_max_t-num = ls_arr-num.
       ls_max_t-len = 1.

   ENDIF.

   lv_num = ls_arr-num + 1.

   READ TABLE lt_arr INTO ls_arr2 WITH KEY num = lv_num.

   IF sy-subrc EQ 0.

     ls_max_t-len = ls_max_t-len + 1.

   ELSE.

     IF ls_max_t-len > ls_max-len.

       ls_max-num = ls_max_t-num.
       ls_max-len = ls_max_t-len.

     ENDIF.

     ls_max_t-len = 0.

   ENDIF.

 ENDLOOP.

 WRITE:/ 'Consecutive Subsequence starts: ', ls_max-num, 'and the length is: ', ls_max-len.

Leave a Reply