class Solution {
public:
int maxProfit(vector<int>& prices) {
//Here how to fix the compilation error which says n is variable size and cant be used for
//initialisation and why does this happen that too in only some Problems;.
int n=prices.size();
if(n<=1)
return 0;
int left[n]={0};
int mini = prices[0];
for(int i=1;i<n;i++){
if(prices[i]>mini){
left[i] = max(left[i-1], prices[i]-mini);
}
else{
mini=prices[i];
left[i]=left[i-1];
}
}
int right[n]={0};
int maxi=prices[n-1];
for(int i=n-2;i>=0;i--){
if(prices[i]>maxi){
maxi=prices[i];
right[i]=right[i+1];
}
else{
right[i] = max(right[i-1], maxi-price[i]);
}
}
int res=0;
for(int i=0;i<n;i++){
res=max(res, left[i]+right[i]);
}
return res;
}
};
Asked
Active
Viewed 35 times
-1

Serge Ballesta
- 143,923
- 11
- 122
- 252
-
1Use std::vector
for variable sized arrays. – 273K Mar 24 '21 at 15:36 -
C++ doesn't really have [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array), like you try to create for `left` and `right`. – Some programmer dude Mar 24 '21 at 15:37
-
1Does this answer your question? [variable-sized object may not be initialized](https://stackoverflow.com/questions/9688219/variable-sized-object-may-not-be-initialized) – 273K Mar 24 '21 at 15:38
1 Answers
1
From Declerators (8): noptr-declarator [ constexpr(optional) ] attr(optional) (8)
the array size is a const expression.
From Array declaration about the size
an integral constant expression (until C++14) a converted constant expression of type std::size_t (since C++14), which evaluates to a value greater than zero
You can't use a runtime variable for this but prices.size()
is a runtime variable.
Either use a compile time constant size, a std::vector
or dynamic memory allocation.