0

I am trying to solve Longest Bi tonic sub-sequence problem, although I got the running code from various sites, but I cannot figure out why my solution is not working. I am trying to return the max length sub-sequence. I have created a type named array which stores the value for every element, if it is included in ascending sub-sequence or descending sub-sequence.

#include <bits/stdc++.h>
#define li long int

int longestBitonicSubarray(int *input, int n) {
  li* output = new li[n];
  li* type = new li[n];
  output[0] = 1;
  type[0] = 0;
  /*
    type when 1 means order is ascending
    type when 2 means order is descending
    type when 0 not decided
  */
  for(li i=1;i<n;i++) {
    output[i] = 1;
    type[i] = 0;

    for(li j=i-1;j>=0;j--) {
      if(type[j] == 0 || type[j] == 1) {
        if(input[j] < input[i]) {
          li pos_ans = output[j] + 1;
          if(output[i] < pos_ans) {
            output[i] = pos_ans;
            type[i] = 1;
          }
        } else if(input[j] > input[i]) {
          li pos_ans = output[j] + 1;
          if(output[i] < pos_ans) {
            output[i] = pos_ans;
            type[i] = 2;
          }
        }
      } else {
        if(input[j] > input[i]) {
          li pos_ans = output[j] + 1;
          if(output[i] < pos_ans) {
            output[i] = pos_ans;
            type[i] = 2;
          }
        }
      }
    }
  }

  li ans = *max_element(output,output+n);
  delete [] output;
  delete [] type;
  return ans;
}
Aakash
  • 1
  • 1
  • This is literally the second post within 15 minutes that has the [same issues](https://stackoverflow.com/questions/58824571/given-an-array-of-positive-numbers-find-the-maximum-subsequence-sum-given-su#comment103926707_58824571) – PaulMcKenzie Nov 12 '19 at 18:59
  • Why `new` instead of `std::vector` or `std::array` if you know the size of it? That `#define` is also something you don't want to do. Use the internal C++ names, or `int32_t` if you prefer. Aliases like that cause rampant confusion. – tadman Nov 12 '19 at 19:00
  • 1
    @tadman -- *although I got the running code from various sites,* -- That answers your question, I guess. – PaulMcKenzie Nov 12 '19 at 19:01
  • Are you using anything from ``? You should develop a habit of only including header files that you need; don't include monolithic headers. – Thomas Matthews Nov 12 '19 at 21:04
  • Your `ll` macro actually slows down the compilation. The preprocessor has to substitute every instance of `ll` with `long long` before compilation. If you need macros like this, take a keyboarding (typing) class. – Thomas Matthews Nov 12 '19 at 21:07
  • okay, I will change the headers, remove the macro and use vector instead of new , but all this will make my code fast not work. – Aakash Nov 13 '19 at 05:53

0 Answers0