程序范式作业
总共三个作业第一个和第二个很简单。
第三个竟然是力扣题,用的是动态规划,我这种菜鸡怎么会啊,看了解析半天看不懂
#include<iostream>
#include<string>
#include <vector>
using namespace std;
int get_the_best_profit(vector<int> & prices);
int main()
{
int profit;
int length;
int * answer;
cout<<"Enter the length of the array"<<endl;
//while(1){
cin>>length;
//}//make sure the length is between 1 and 105
vector <int> prices(length);
cout<<"Enter the price."<<endl;
for(int i=0;i<length;i++)
{
int price;
//while(1){
cin>>price;
prices[i] = price;
//}//make sure the stock price is between 0 and 104
}
profit=get_the_best_profit(prices);
cout<<"The max profit is:"<<profit<<endl;
return 0;
}
int get_the_best_profit(vector<int>& prices)
{
if (prices.size() == 0) {
return 0;
}
int n = prices.size();
// f[i][0]: 手上持有股票的最大收益
// f[i][1]: 手上不持有股票,并且处于冷冻期中的累计最大收益
// f[i][2]: 手上不持有股票,并且不在冷冻期中的累计最大收益
vector<vector<int>> f(n, vector<int>(3));
f[0][0] = -prices[0];
for (int i = 1; i < n; ++i) {
f[i][0] = max(f[i - 1][0], f[i - 1][2] - prices[i]);
f[i][1] = f[i - 1][0] + prices[i];
f[i][2] = max(f[i - 1][1], f[i - 1][2]);
}
return max(f[n - 1][1], f[n - 1][2]);
}
emmm
这个函数的算法实现目前还是很懵,明天再看看吧。明天给出这个的详解。
vector类
在图书馆看了一个小时总结一下吧
第五章集合类,总共介绍了五个Vector,Stack、Queue、Map、Set。
目前就看了Vector这个,头文件中要加#include<vector>
是一种参数化的类,用了模板。
声明
一、Vector<int> vec;
二、vector<int> vec(int n);\\声明一个确定的大小的数组
三、二维结构的声明:vector<vector<int>> f(n, vector<int>(3));\\二维的结构,有n个vector对象,内部的vector对象含有九个元素基类型为int
四、声明加初始化 vector<int> vec={1,2,3};
vector操作
vec.add(10);在对象的末尾加一个元素
vec.remove(0);删去该索引的元素
vec.insert(n,10);
vec.set(3,70);
支持数组的形式,vec[1]=2;
作为参数传递vector
int get_the_best_profit(vector<int>& prices);
使用引用调用,更加高效不用繁琐的复制一遍vector中庞大的数据。
可以直接对prices中的数据进行操作。