I am new to Prolog and trying to resolve instances of the problem with maximum subaram .
I have the following pretty elegant C ++ code:
int maxSubArray(vector<int> List)
{
int maxsofar = 0;
int maxendinghere = 0;
for (int i = 0; i < List.size(); i++)
{
maxendinghere = max(maxendinghere+List[i], 0);
maxsofar = max(maxsofar, maxendinghere);
}
return maxsofar;
}
And here is my Prolog code:
max(X,X,X).
max(X,Y,X) :- X>Y.
max(X,Y,Y) :- X<Y. %define max function
prev(L,T,H) :-
reverse(L,[H|T1]),
reverse(T,T1). %split L to H(last element) and T(the remaining list)
f([],0,0).
f(L,M,N) :-
f(L1,M1,N1),
prev(L,L1,E),
max(M1,N,M),
max(K,0,N),
K is N1+E.
I am trying to get the maximum amount from f(L,M,N)where Lis the list, the Mresult (the maximum amount, as well as the maxsofar variable in C ++ code) I want to get Nis an intermediate variable like "maxendinghere" in C ++ code. I want to get the answer Lfrom his previous list L1, and the relation of variables is exactly the same as the C ++ code.
However, the following query does not work:
?- f([1,2,3],X,Y).
is/2: Arguments are not sufficiently instantiated
I do not know where the problem is.