The sword refers to the offer on the 8th day of dynamic programming (simple)
The sword refers to Offer 10- I. Fibonacci sequence
topic ideas
Obviously it is a recursive relationship, just write it directly
topic code
c++ code
class Solution {
private:
int mod = 1e9+7;
int f[110];
public:
int fib(int n) {
f[0]=0,f[1]=1;
for(int i=2;i<=n;i++){
f[i] = (f[i-1] + f[i-2])%mod;
}
return f[n];
}
};
python code
class Solution:
def fib(self, n: int) -> int:
a = 0
b = 1
c = 0
mod = 1e9+7
if not n :
return a
elif n==1 :
return b
else:
for i in range(2,n+1):
c = (a+b)%mod
a = b%mod
b = c%mod
return int(c)
The sword refers to Offer 10- II. Frog jumping steps
topic ideas
Similar to the previous topic. It's nothing more than n steps, you can only go up from the n-1th and n-2th steps
topic code
c++ code
class Solution {
private:
int mod = 1e9+7;
int f[110];
public:
int numWays(int n) {
f[0]=1,f[1]=1,f[2]=2;
for(int i=2;i<=n;i++){
f[i] = (f[i-1] + f[i-2])%mod;
}
return f[n];
}
};
python code
class Solution:
def numWays(self, n: int) -> int:
a = 1
b = 1
c = 0
mod = 1e9+7
if not n :
return a
elif n==1 :
return b
else:
for i in range(2,n+1):
c = (a+b)%mod
a = b%mod
b = c%mod
return int(c)
The sword refers to Offer 63. The maximum profit of the stock
topic ideas
A typical problem, two arrays, the first group represents the maximum profit after buying the stock, and the second group represents the maximum profit after selling
topic code
c++ code
class Solution {
public:
int maxProfit(vector<int>& prices) {
int s[100010],b[100010];
int n = prices.size();
for(int i=0;i<100010;i++){
s[i]=-100000000;
b[i]=0;
}
for(int i=1;i<=n;i++){
s[i]=max(s[i-1],0-prices[i-1]);
b[i]=max(b[i-1],s[i]+prices[i-1]);
//cout<<s[i]<<" "<<b[i]<<endl;
}
return b[n];
}
};
python code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
s = [-1000000]*100010
b = [0]*100010
n = len(prices)
for i in range(1,n+1):
s[i] = max(s[i-1],0-prices[i-1])
b[i] = max(b[i-1],s[i]+prices[i-1])
return b[n]
If this article is helpful to my friends, I hope to give a like and support~ Thank you very much~