Skip to content

Instantly share code, notes, and snippets.

View ruihuang888's full-sized avatar

Terry (Rui) Huang ruihuang888

View GitHub Profile
@ruihuang888
ruihuang888 / max_power.py
Created February 9, 2023 12:41
Solution to find the maximum power needed for an automated water distribution in a wheat farm
def max_power(fields, towers):
# Initialize two pointers 'i' and 'j' to traverse both the 'fields' and 'towers' lists respectively.
i = j = 0
# Initialize a variable 'max_distance' to store the maximum distance between a field and a tower.
max_distance = 0
# Run a loop until either of the two pointers reaches the end of its respective list.
while i < len(fields) and j < len(towers):
# Calculate the absolute difference between the current field and tower.
curr_distance = abs(fields[i] - towers[j])
# Update 'max_distance' with the maximum value of the current difference and the existing 'max_distance'.
@ruihuang888
ruihuang888 / maximize_As_DP.py
Created February 9, 2023 12:37
Solution to the 'Maximize the number of As' problem using Dynamic Programming in Python
def maxA(N: int) -> int:
# Create an array to store the maximum number of As that can be printed
# in each step
dp = [0] * (N + 1)
# Fill the dp array
for i in range(1, N + 1):
# In the first step, we can print only 1 'A'
dp[i] = dp[i-1] + 1
for j in range(i-3, 0, -1):
@ruihuang888
ruihuang888 / find_x_binary_search.py
Last active February 9, 2023 12:38
Finding the first number of teaspoons of sugar that will make a cake too sweet using binary search algorithm
# Function to find the first number of teaspoons of sugar that will make the cake too sweet
def find_x(n, isTooSweet):
# Set the lower bound to be 1 teaspoon
lower = 1
# Set the upper bound to be n teaspoons
upper = n
# Repeat until lower bound and upper bound converge to the same value
while lower < upper:
# Find the middle value between the lower and upper bound