-1

The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum.
Following is the pseudo code. It shows an error in line 8.

    int i=1;
        int t=0;
        int j=n-1;
        x=0;
        while(i<=j)
        {
           int s=0; 
           if(arr[i]>=arr[x]) //line 8
           {
               s=arr[i]-arr[x]; //s is to calculate the profit
               if(s>t)
               {
                   t=s; //to find the max profit
               }
               else if(s<t)
               {
                   System.out.println("("+i+","+x+")");
                   x=arr[i];
                   continue;
               }
               i++;
           }
           else if(arr[i]<arr[x])
           {
               x=arr[i];
               i++;
           }
        }    
Boken
  • 4,825
  • 10
  • 32
  • 42
HarshRaj
  • 11
  • 1
  • 2
    Please read: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Turing85 Jul 16 '20 at 08:09
  • Please show the declaration and initialization of the array. – NomadMaker Jul 16 '20 at 08:10
  • 1
    A debugger is a tool which is almost built in in every IDE which helps you to understand your program. What it does is it simply stop the program at each line and shows you your variables and their values at every stage of the program. Watch a video tutorial to understand it better. It is a must have skill, to debug your program, every dev should master – René Jul 16 '20 at 08:19
  • 1
    What is `x`? It's seems to be an index (you use `arr[x]` in several places), but on the other hand you assign it value value from the array contents (`x=arr[i];`) – Thomas Kläger Jul 16 '20 at 08:21
  • @ThomasKläger I've used x for the smallest element in the array. Initially it points to the 0th index. Till the value of array elements keep increasing it remains the same, but when a smaller value is encountered then x is updated with that index of i. – HarshRaj Jul 16 '20 at 08:30
  • If x becomes 40, then you're indexing your array with index 40 while it contains only 7 in the case you just provided. – Maaddy Jul 16 '20 at 08:34
  • @Maaddy ohh shit yes. Thanks for pointing out. – HarshRaj Jul 16 '20 at 08:36

1 Answers1

0

You are doing x=arr[i] and then in if-condition

if (arr[i]>=arr[x])

this x will lead to index out of bound exception

An example : try {10,5,15} , it will assign x=arr[i] as x=5(for i=1),now when the loop runs for i=2 , it will look for arr[5] which does not exist.

A fix could be to compare arr[i]>=x rather than arr[i]>=arr[x]

Shubham Kumar
  • 92
  • 1
  • 12