Skip to content

Instantly share code, notes, and snippets.

@bcho
Created December 22, 2014 14:25
Show Gist options
  • Select an option

  • Save bcho/276b597a275982caf2ec to your computer and use it in GitHub Desktop.

Select an option

Save bcho/276b597a275982caf2ec to your computer and use it in GitHub Desktop.
maxsum(A, B) :-
maxsum_aux(A, 0, 0, B).
% Kadane's algorithm
maxsum_aux([Elem|Tail], F, M, ANS) :-
choose_max(0, F + Elem, Fx),
choose_max(M, Fx, Mx),
maxsum_aux(Tail, Fx, Mx, ANS).
maxsum_aux([], F, M, ANS) :-
ANS is M.
choose_max(A, B, M) :- ( A =< B -> M = B; M is A).
@llaisdy
Copy link
Copy Markdown

llaisdy commented Dec 22, 2014

很好! Very nice! I have three minor comments/suggestions:

  1. For the second maxsum_aux/4 clause:
maxsum_aux([], F, M, M).
  1. For choose_max/3:
choose_max(A, B, B) :- A =< B.
choose_max(A, B, A) :- A > B.

% using cut can simplify the code a little, but I don't like using cut, e.g.:
% choose_max(A, B, B) :- A =< B, !.
% choose_max(A, B, A).
  1. Add a test:
maxsum([-2, 1, -3, 4, -1, 2, 1, -5, 4], 6).

谢谢!

Ivan (aka @prologinfo)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment