 # Best time to Buy and sell stock

I am doing this question from leetcode where I am getting an error .can somebody help me to find it?I have tried dry running it 2 times sitll i am not able to debug it.

``````class Solution {
public:
int maxProfit(vector<int>& prices) {
long long int n=prices.size();

vector<int> profit(n,0);
vector<int> suffix(n,0);
suffix[n-1]=prices[n-1];
profit[n-1]=0;

for(long long int i=n-2;i>=0;i++)
{
suffix[i]=max(suffix[i+1],prices[i+1]);
profit[i]=suffix[i]-prices[i];
}

int ans =0;
for(long long int i=0;i<n;i++)
ans=max(ans,profit[i]);

return ans;

}
};
``````

i-- in first for loop

can you give me any on tips how can i avoid making such mistakes?  i tried debugging it for long time by checking each line still i do these mistakes(and this is not the first time  )

Just running the sample input with proper debug flags would have spotted this immediately:

``````#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
int maxProfit(vector<int>& prices) {
long long int n=prices.size();

vector<int> profit(n,0);
vector<int> suffix(n,0);
suffix[n-1]=prices[n-1];
profit[n-1]=0;

for(long long int i=n-2;i>=0;i++)
{
suffix[i]=max(suffix[i+1],prices[i+1]);
profit[i]=suffix[i]-prices[i];
}

int ans =0;
for(long long int i=0;i<n;i++)
ans=max(ans,profit[i]);

return ans;

}
};

int main()
{
vector<int> sampleInputPrices = {7,1,5,3,6,4};
cout << Solution().maxProfit(sampleInputPrices) << endl;
}
``````
``````[simon@simon-laptop][19:05:01]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh
Compiling abhinav_700-blah.cpp
+ g++ -std=c++17 abhinav_700-blah.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv -fno-sanitize-recover
+ set +x
Successful
[simon@simon-laptop][19:05:04]
[~/devel/hackerrank/otherpeoples]>./a.out
/usr/include/c++/7/debug/vector:417:
Error: attempt to subscript container with out-of-bounds index 6, but
container only holds 6 elements.

Objects involved in the operation:
sequence "this" @ 0x0x7ffe48851f90 {
type = std::__debug::vector<int, std::allocator<int> >;
}
Aborted (core dumped)
``````

My compiler doesn’t throw such verbose error message. What debugger you are using?

All the information you need is there Can you tell me which flag is responsible?

In this particular case: `-D_GLIBCXX_DEBUG`

Ok thanks!

1 Like

so i guess i sould start learning debugging