max_sub_sequence.hxx
Go to the documentation of this file.
1 /*===========================================================================================================
2  *
3  * HUC - Hurna Core
4  *
5  * Copyright (c) Michael Jeulin-Lagarrigue
6  *
7  * Licensed under the MIT License, you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * https://github.com/Hurna/Hurna-Core/blob/master/LICENSE
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License is
13  * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and limitations under the License.
15  *
16  * The above copyright notice and this permission notice shall be included in all copies or
17  * substantial portions of the Software.
18  *
19  *=========================================================================================================*/
20 #ifndef MODULE_SEARCH_MAX_SUB_SEQUENCE_HXX
21 #define MODULE_SEARCH_MAX_SUB_SEQUENCE_HXX
22 
23 // STD includes
24 #include <iterator>
25 #include <utility>
26 
27 namespace huc
28 {
29  namespace search
30  {
49  template <typename IT,
50  typename Distance = std::minus<typename std::iterator_traits<IT>::value_type>,
51  typename Compare = std::greater<typename std::iterator_traits<IT>::value_type>>
52  std::pair<int, int> MaxSubSequence(const IT& begin, const IT& end)
53  {
54  if (std::distance(begin, end) < 2)
55  return std::pair<int, int>(-1, -1);
56 
57  int minValIdx = 0;
58  std::pair<int, int> indexes(minValIdx, minValIdx);
59  auto minSum = static_cast<typename std::iterator_traits<IT>::value_type>(0);
60  auto currSum = *begin;
61  auto maxSum = *begin;
62 
63  int currentIdx = 1;
64  for (auto it = begin + 1; it != end; ++it, ++currentIdx)
65  {
66  currSum += *it;
67 
68  // keep track of the minimum sum and its first value index
69  if (Compare()(minSum, currSum))
70  {
71  minValIdx = currentIdx;
72  minSum = currSum;
73  }
74 
75  // Keeps track of the maximal sub array and its end value index
76  auto curMax = Distance()(currSum, minSum);
77  if (Compare()(curMax, maxSum))
78  {
79  indexes.first = minValIdx + ((*(begin + minValIdx) < 0) ? 1 : 0);
80  indexes.second = currentIdx;
81  maxSum = Distance()(currSum, minSum);
82  }
83  }
84 
85  return indexes;
86  }
87  }
88 }
89 
90 #endif // MODULE_SEARCH_MAX_SUB_SEQUENCE_HXX
std::pair< int, int > MaxSubSequence(const IT &begin, const IT &end)