Skip to content

Instantly share code, notes, and snippets.

@munguial
Created April 7, 2020 06:25
Show Gist options
  • Save munguial/2b51046afd455824ce976d2f2303aff8 to your computer and use it in GitHub Desktop.
Save munguial/2b51046afd455824ce976d2f2303aff8 to your computer and use it in GitHub Desktop.
Max sum of K numbers taken from beginning or end of the array
import unittest
class Program:
def maxSubArrayWithKElements(self, array, k):
j = len(array) - k
currSum = minSum = sum(i for i in array[:j])
for i in range(j, len(array)):
currSum += array[i]
currSum -= array[i - j]
minSum = min(minSum, currSum)
return sum(array) - minSum
class Test(unittest.TestCase):
def test_one(self):
program = Program()
inputArray = [1, 6, 2, 3]
self.assertEqual(program.maxSubArrayWithKElements(inputArray, 2), 7)
def test_two(self):
program = Program()
inputArray = [5, 1, 6, 2, 3]
self.assertEqual(program.maxSubArrayWithKElements(inputArray, 3), 12)
def test_three(self):
program = Program()
inputArray = [5, 1, 6, 2, 3]
self.assertEqual(program.maxSubArrayWithKElements(inputArray, 2), 8)
def test_four(self):
program = Program()
inputArray = [5, 1, 6, 2, 3]
self.assertEqual(program.maxSubArrayWithKElements(inputArray, 4), 16)
def test_five(self):
program = Program()
inputArray = [1, 1, 2, 1, 0]
self.assertEqual(program.maxSubArrayWithKElements(inputArray, 3), 4)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment