Created
April 7, 2020 06:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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