#if !defined  HAVE_MAX_SUBRANGE_SUM_H__
#define       HAVE_MAX_SUBRANGE_SUM_H__
// This file is part of the FXT library.
// Copyright (C) 2016, 2020 Joerg Arndt
// License: GNU General Public License version 3 or later,
// see the file COPYING.txt in the main directory.

#include "fxttypes.h"

template <typename Type>
inline Type max_subrange_sum(Type * const x, ulong n)
// Return largest sum of any (contiguous) subrange.
// From: Jon Bentley, Programming pearls, Addison-Wesley, 1984, p. 74.
// Cf. https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm
// Cf. https://leetcode.com/problems/maximum-subarray/discuss/447660/Java-Full-Explanations-DPKadane's-plus-max-subarray-indices-and-Divide-and-Conquer
{
    Type msf = 0;  // MaxSoFar
    Type meh = 0;  // MaxEndingHere
    for (ulong j=0; j<n; ++j)
    {
        Type t = meh + x[j];
        meh = ( t > 0 ? t : 0 );
        msf = ( msf > meh ? msf : meh );
    }
    return msf;
}
// -------------------------

#endif // !defined HAVE_MAX_SUBRANGE_SUM_H__
