Skip to content

Instantly share code, notes, and snippets.

@israelst
Created June 20, 2012 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israelst/2961114 to your computer and use it in GitHub Desktop.
Save israelst/2961114 to your computer and use it in GitHub Desktop.
Max sum
def max_sum(vector):
return cubic_solution(vector)
def cubic_solution(vector):
max_sum = 0
for i in range(len(vector) + 1):
for j in range(i):
partial_sum = sum(vector[j:i])
max_sum = max(partial_sum, max_sum)
return max_sum
import unittest
from max_sum import max_sum
class Tests(unittest.TestCase):
def assert_max_sum(self, vector, sum):
self.assertEqual(max_sum(vector), sum)
def test_only_negative_elements(self):
self.assert_max_sum([-41], 0)
def test_one_element(self):
self.assert_max_sum([31], 31)
def test_only_positive_elements(self):
self.assert_max_sum([31, 41], 72)
def test_one_positive_and_one_negative_element(self):
self.assert_max_sum([31, -41], 31)
self.assert_max_sum([-41, 31], 31)
def test_positives_and_negatives_elements(self):
self.assert_max_sum([31, -41, 59, 26, -53, 58, 97, -93, -23, 84], 187)
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment