'Facing runtime error in Buy and sell stock
This is the code to get maximum profit through buying and selling of stocks. Stock prices are given in the form of an array. Different array indexes represent prices on different days.
#include <vector>
class Solution
{
int findMin(vector<int> prices)
{
int mini = 0;
int min = prices[0];
for (int i = 0; i < prices.size(); i++)
{
if (min > prices[i])
{
min = prices[i];
mini = i;
}
}
int end = prices.size() - 1;
if (mini == end)
{
prices.pop_back();
findMin(prices);
}
return mini;
};
public:
int maxProfit(vector<int> &prices)
{
int minimumIndex = findMin(prices);
int max = prices[minimumIndex];
for (int i = minimumIndex; i < prices.size(); i++)
{
if (max < prices[i])
{
max = prices[i];
}
}
return max - prices[minimumIndex];
}
};
This is the issue given by compiler:
Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
