Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
nhudinhtuan / highest_sum_brute_force.py
Last active March 30, 2020 05:51
the highest sum of any k consecutive elements in the array
def highestSum(arr, k):
highest_sum = float('-inf')
n = len(arr)
# n must not be smaller than k
if n < k:
return -1
# subarray starts at i
for i in range(n - k + 1):
@nhudinhtuan
nhudinhtuan / highest_sum_sliding_window.py
Last active December 28, 2021 02:15
the highest sum of any k consecutive elements in the array
def highestSum(arr, k):
highest_sum = float('-inf')
n = len(arr)
# n must not be smaller than k
if n < k:
return -1
# Compute sum of first window of size k
window_sum = sum([arr[i] for i in range(k)])
@nhudinhtuan
nhudinhtuan / is_valid_number.py
Created March 29, 2020 08:16
is valid number
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
#define state transition tables
states = [
# no State (0)
@nhudinhtuan
nhudinhtuan / atoi.py
Created March 29, 2020 03:59
String to Integer (atoi)
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
def in_range(num):
if num > 2 ** 31 - 1: return 2 ** 31 - 1
if num < -2**31: return -2**31