东方财富1:交叉字符串
不负责任的直接放上来代码,原题解讲的比较清楚:
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n1 = len(s1)
n2 = len(s2)
n3 = len(s3)
if n1 + n2 != n3: return False
dp = [[False] * (n2 + 1) for _ in range(n1 + 1)]
dp[0][0] = True
# 第一行
for j in range(1, n2 + 1):
dp[0][j] = (dp[0][j - 1] and s2[j - 1] == s3[j - 1])
# 第一列
for i in range(1, n1 + 1):
dp[i][0] = (dp[i - 1][0] and s1[i - 1] == s3[i - 1])
# print(dp)
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (
dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])
# print(dp)
return dp[-1][-1]
东方财富2:买卖股票的最佳时机
原题解(python3)——leetcode:买卖股票的最佳时机(买卖一次)
这题与原题略有不同,笔试题是可以买卖两次(原题是买卖一次),因此我想到的思路是可以将数组拆分,用左数组的最大收益加上右边数组的最大收益,代码如下:
# 找一次买卖时的最大值
def helper(prices):
r, m = 0, float('inf') # r代表收益, m代表最小值
for p in prices:
r, m = max(r, p - m), min(m, p)
return r
prices = [7, 1, 5, 3, 6, 4]
n = len(prices)
max_ = 0
for i in range(n):
max_ = max(helper(prices[0:i]) + helper(prices[i:]), max_)
print(max_)