Skip to content

Instantly share code, notes, and snippets.

@coreyjs
Last active August 8, 2022 15:30
Show Gist options
  • Save coreyjs/d44d467a0bf08513c57d8a44801fa57c to your computer and use it in GitHub Desktop.
Save coreyjs/d44d467a0bf08513c57d8a44801fa57c to your computer and use it in GitHub Desktop.
def set_value(ary, index: int) -> int:
if index < len(ary):
return ary[index]
else:
return None
def array_sum(ary) -> int:
if len(ary) == 0:
return 0
curr_index = 0
current_sum, prev_sum = ary[curr_index], 0
slow_iter = curr_index + 3
fast_iter = curr_index + 4
current_val, slow_val, fast_val = 0, 0, 0
while (curr_index < len(ary)):
prev_sum = current_sum
current_val = ary[curr_index]
# look ahead and set our +3 val
slow_val = set_value(ary=ary, index=(curr_index + 3))
fast_val = set_value(ary=ary, index=(curr_index + 4))
# if we are out of bounds on both iters, break out.
if not slow_val and not fast_val:
break
# slow will never be None while fast has a value. So check for the
# possibility that fast is None. Our previous check above
# will catch the possibility of both being None.
if not fast_val:
current_sum += slow_val
curr_index = curr_index + 3
elif slow_val >= fast_val:
current_sum += slow_val
curr_index = curr_index + 3
elif fast_val > slow_val:
current_sum += fast_val
curr_index = curr_index + 4
# If we have a value that is best case between slow and fast values
# is less than our previous. We can exit as per requirements.
if prev_sum > current_sum:
break;
return max(prev_sum, current_sum)
test_input_1 = [scrubbed]
print(array_sum(ary=test_input_1))
> 140
test_input_2 = [scrubbed]
print(array_sum(ary=test_input_2))
> 458
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment