1

I am trying to maximize this function in c++:

enter image description here

I have put this in the function:

int F(int n , int T ){

  if( T >= 0  &&  n == 0){

      return 0;

  }else if( T < 0){

      return INT_MIN;

  } else if(T >= 0  &&  n > 0){

      for(int i = 0 ; i <= m[n-1] ; i++){

       ganancia = max(i * v[n-1] + F(n-1,T-i*t[n-1]),ganancia );

      }

  }

}

but when I put on n 3 , T 8, t {1, 2, 2}, v {12, 15, 30} and finally on m{3, 3, 2} my program return 2, when it had to return 99.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100

2 Answers2

1

You have three branches in the function, but only two return values. If you fail to return a value you will have undefined behavior. You need to return a value from all branches.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Now I have my code like this:

int F(int n , int T ){

  if( T >= 0  &&  n == 0){

      return 0;

  }else if( T < 0){

      return INT_MIN;

  } else if(T >= 0  &&  n > 0){

      for(int i = 0 ; i <= m[n-1]-1 ; i++){

       return (max(i * v[n-1] + F(n-1,T-i*t[n-1]),(i+1) * v[n-1] + F(n-1,T- (i+1)*t[n-1]) ));

      }

  }

}

And now it is showing my program 12 instead of 13, at least I have left that 2 value. Thanks!