当前位置:网站首页>Sword finger offer 10 Ⅰ 10Ⅱ. 63 dynamic planning (simple)
Sword finger offer 10 Ⅰ 10Ⅱ. 63 dynamic planning (simple)
2022-06-26 14:13:00 【hedgehog:】
10.Ⅰ
subject :
idea : F(N) = F(N - 1) + F(N - 2), Recursive time complexity is too high , Use dynamic programming , Move ab.
Code :
class Solution {
public int fib(int n) {
int a = 0, b = 1, sum;
for(int i = 0; i < n; i++){
sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return a;
}
}
result :
10.Ⅱ
subject :
idea :( Steal a picture )
still fib problem , It's just f(0)=f(1)=1.
Code :
class Solution {
public int numWays(int n) {
int a = 1, b = 1, sum;
for(int i = 0; i < n; i++){
sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return a;
}
}
result :
63.
subject :
idea :( Steal a picture )
Remember to buy at the cheapest time !
Code :
// violence Time complexity is too high
class Solution {
public int maxProfit(int[] prices) {
int max=0;
for(int i=prices.length-1;i>=0;i--){
for(int j=i-1;j>=0;j--){
int tmp=prices[i]-prices[j];
if(tmp>max)
max=tmp;
}
}
return max;
}
}
//DP. Buy at the lowest price
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int max=0;
for(int i=0;i<prices.length;i++){
if(prices[i]<min)
min=prices[i];
else if(prices[i]-min>max)
max=prices[i]-min;
}
return max;
}
}
result :
边栏推荐
猜你喜欢
windows版MySQL软件的安装与卸载
Exercise set 1
Pycharm远程连接服务器来跑代码
程序员必备,一款让你提高工作效率N倍的神器uTools
I met the problem of concurrent programming in an interview: how to safely interrupt a running thread
Pytorch based generation countermeasure Network Practice (7) -- using pytorch to build SGAN (semi supervised GaN) to generate handwritten digits and classify them
New specification of risc-v chip architecture
Generation and rendering of VTK cylinder
Build your own PE manually from winpe of ADK
ThreadLocal巨坑!内存泄露只是小儿科...
随机推荐
Create your own cross domain proxy server
[sdoi2013] forest
character constants
Difference between classification and regression
同花顺股票开户选哪个证券公司是比较好,比较安全的
Introduction to 26 papers related to CVPR 2022 document image analysis and recognition
Logical operation
Is expression of D
D check type is pointer
Global variable vs local variable
[wc2006] director of water management
Insect operator overloaded a fun
Matlab programming related knowledge
Basic type of typescript
Installation and uninstallation of MySQL software for windows
Self created notes (unique in the whole network, continuously updated)
Is it safe to open a securities account? Is there any danger
Range of types
What is the use of index aliases in ES
Never use redis expired monitoring to implement scheduled tasks!