Skip to content

Test #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Sep 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions easy/1.two_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def twoSum(self, nums: List[int], target: int) -> List[int]:
return [result[res], index]
else:
result[value] = index


# two-pass hash table [Accepted]
#
#
# # two-pass hash table [Accepted]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# generate a dict which key is element, value is index
Expand All @@ -41,12 +41,38 @@ def twoSum(self, nums: List[int], target: int) -> List[int]:
res = target - nums[index]
if res in nums_dict and nums_dict[res] != index:
return [index, nums_dict[res]]


# Bruce Force [Not Accepted, Time exceeded]
#
#
# # Bruce Force [Not Accepted, Time exceeded]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for idx1 in range(len(nums)):
for idx2 in range(idx1 + 1, len(nums)):
if nums[idx1] + nums[idx2] == target:
return [idx1, idx2]

# two pointers
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
sorted_nums = sorted(nums)
lo = 0
hi = len(nums) -1
while lo < hi:
total = sorted_nums[lo] + sorted_nums[hi]
left = sorted_nums[lo]
right = sorted_nums[hi]
if total > target:
while lo < hi and sorted_nums[hi] == right:
hi -= 1
elif total < target:
while lo < hi and sorted_nums[lo] == left:
lo += 1
elif total == target:
res = []
for index, item in enumerate(nums):
if item in [left, right]:
res.append(index)
return res
return []


75 changes: 57 additions & 18 deletions easy/121.best_time_to_buy_and_sell_stock.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,27 +35,66 @@
# [End of Description]:

# brute force(Not Accepted, Timeout)
# In formal terms, we need to find max(prices[j]−prices[i]), for every i and j such that j > i.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
max_profit = 0
for i in range(n):
for j in range(i + 1, n):
if prices[j] - prices[i] > max_profit:
max_profit = prices[j] - prices[i]
return max_profit
# # In formal terms, we need to find max(prices[j]−prices[i]), for every i and j such that j > i.
# class Solution:
# def maxProfit(self, prices: List[int]) -> int:
# n = len(prices)
# max_profit = 0
# for i in range(n):
# for j in range(i + 1, n):
# if prices[j] - prices[i] > max_profit:
# max_profit = prices[j] - prices[i]
# return max_profit
#
#
# # one pass(We need to find the largest peak following the smallest valley)
# class Solution:
# def maxProfit(self, prices: List[int]) -> int:
# n = len(prices)
# max_profit = 0
# min_price = float("inf")
# for i in range(n):
# if prices[i] < min_price:
# min_price = prices[i]
# else:
# max_profit = max(max_profit, prices[i] - min_price)
# return max_profit

# dp template
# class Solution:
# def maxProfit(self, prices: List[int]) -> int:
# n = len(prices)
# # initial dp array
# dp = []
# for _ in range(n):
# inner = []
# for i in range(2):
# inner.append(i)
# dp.append(inner)
# # base case
# for i in range(n):
# if i - 1 == -1:
# dp[i][0] = 0
# # dp[i][0] =
# # max(dp[-1][0], dp[-1][1] + price[0])
# # max(0, -inf + price[0]) = 0
# dp[i][1] = -prices[i]
# # dp[i][1] =
# # max(dp[-1][1], -price[i])
# # max(-inf, -price[i]) = -price[i]
# continue
# dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
# dp[i][1] = max(dp[i-1][1], -prices[i])
# return dp[n-1][0]

# one pass(We need to find the largest peak following the smallest valley)
# actually we just need to store the previous two value
# no need to use a two-dimension array
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
max_profit = 0
min_price = float("inf")
dp_i_0 = 0
dp_i_1 = -float("inf")
for i in range(n):
if prices[i] < min_price:
min_price = prices[i]
else:
max_profit = max(max_profit, prices[i] - min_price)
return max_profit
dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])
dp_i_1 = max(dp_i_1, -prices[i])
return dp_i_0
20 changes: 17 additions & 3 deletions easy/122.best_time_to_buy_and_sell_stock_ii.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,27 @@ def maxProfit(self, prices: List[int]) -> int:
return maxProfit


# a mathmatics trick here
# peak1 - valley1 + peak2 - valley2
# p1-p0+p2-p1+p3-p2+...+p(n)-p(n-1) = p(n) - p0
## a mathmatics trick here
## peak1 - valley1 + peak2 - valley2
## p1-p0+p2-p1+p3-p2+...+p(n)-p(n-1) = p(n) - p0
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
maxProfit += prices[i] - prices[i - 1]
return maxProfit


class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp_i_0 = 0
dp_i_1 = -float("inf")
n = len(prices)
for i in range(n):
# markdown the previous one
# which is different from the second dp_i_0
temp = dp_i_0
dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])
dp_i_1 = max(dp_i_1, temp - prices[i])
return dp_i_0
66 changes: 66 additions & 0 deletions easy/123.best_time_to_buy_and_sell_stock_iii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Best Time to Buy and Sell Stock III
#
# [Hard] [AC:38.8% 247.6K of 638.4K] [filetype:python3]
#
# Say you have an array for which the ith element is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit. You may complete at most two transactions.
#
# Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy
# again).
#
# Example 1:
#
# Input: prices = [3,3,5,0,0,3,1,4]
#
# Output: 6
#
# Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
#
# Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
#
# Example 2:
#
# Input: prices = [1,2,3,4,5]
#
# Output: 4
#
# Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
#
# Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the
# same time. You must sell before buying again.
#
# Example 3:
#
# Input: prices = [7,6,4,3,1]
#
# Output: 0
#
# Explanation: In this case, no transaction is done, i.e. max profit = 0.
#
# Example 4:
#
# Input: prices = [1]
#
# Output: 0
#
# Constraints:
#
# 1 <= prices.length <= 105
#
# 0 <= prices[i] <= 105
#
# [End of Description]:

# stock template
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp_i10 = dp_i20 = 0
dp_i11 = dp_i21 = -float("inf")
for price in prices:
dp_i20 = max(dp_i20, dp_i21 + price)
dp_i21 = max(dp_i21, dp_i10 - price)
dp_i10 = max(dp_i10, dp_i11 + price)
dp_i11 = max(dp_i11, -price)

return dp_i20
78 changes: 78 additions & 0 deletions easy/15.3sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# 3Sum
#
# [Medium] [AC:27.1% 1M of 3.8M] [filetype:python3]
#
# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique
# triplets in the array which gives the sum of zero.
#
# Notice that the solution set must not contain duplicate triplets.
#
# Example 1:
#
# Input: nums = [-1,0,1,2,-1,-4]
#
# Output: [[-1,-1,2],[-1,0,1]]
#
# Example 2:
#
# Input: nums = []
#
# Output: []
#
# Example 3:
#
# Input: nums = [0]
#
# Output: []
#
# Constraints:
#
# 0 <= nums.length <= 3000
#
# -105 <= nums[i] <= 105
#
# [End of Description]:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
sorted_nums = sorted(nums)
return self.nSumTarget(sorted_nums, 3, 0, 0)

def nSumTarget(self, nums: List[int], n: int, start: int, target: int) -> List[List[int]]:
sz = len(nums)
res: List[List[int]] = []
if n < 2 or sz < n:
return res
if n == 2:
lo = start
hi = sz -1
while lo < hi:
total = nums[lo] + nums[hi]
left = nums[lo]
right = nums[hi]
if total == target:
res.append([left, right])
while lo < hi and nums[lo] == left:
lo += 1
while lo < hi and nums[hi] == right:
hi -= 1
elif total < target:
while lo < hi and nums[lo] == left:
lo += 1
elif total > target:
while lo < hi and nums[hi] == right:
hi -= 1
else:
i = start
while i < sz:
sub = self.nSumTarget(nums, n - 1, i + 1, target - nums[i])
for item in sub:
item.append(nums[i])
res.append(item)
while (i < sz - 1) and (nums[i] == nums[i + 1]):
i += 1
i += 1
return [sorted(item) for item in res]




74 changes: 74 additions & 0 deletions easy/18.4sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# 4Sum
#
# [Medium] [AC:33.9% 352.6K of 1M] [filetype:python3]
#
# Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that
# a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
#
# Note:
#
# The solution set must not contain duplicate quadruplets.
#
# Example:
#
# Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
#
# A solution set is:
#
# [
#
# [-1, 0, 0, 1],
#
# [-2, -1, 1, 2],
#
# [-2, 0, 0, 2]
#
# ]
#
# [End of Description]:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
sorted_nums = sorted(nums)
return self.nSumTarget(sorted_nums, 4, 0, target)

def nSumTarget(self, nums: List[int], n: int, start: int, target: int) -> List[List[int]]:
sz = len(nums)
res = []
if n < 2 or sz < n:
return res
if n == 2:
lo = start
hi = sz - 1
while lo < hi:
total = nums[lo] + nums[hi]
left = nums[lo]
right = nums[hi]
if total > target:
while lo < hi and nums[hi] == right:
hi -= 1
elif total < target:
while lo < hi and nums[lo] == left:
lo += 1
elif total == target:
res.append([left, right])
while lo < hi and nums[lo] == left:
lo += 1
while lo < hi and nums[hi] == right:
hi -= 1
else:
i = start
while i < sz:
sub = self.nSumTarget(nums, n - 1, i + 1, target - nums[i])
for item in sub:
item.append(nums[i])
res.append(item)
while (i < sz - 1) and (nums[i] == nums[i + 1]):
i += 1
i += 1
return [sorted(item) for item in res]






Loading