Leetcode Best Time to Buy and Sell Stock

来源:互联网 发布:南京大学cssci数据库 编辑:程序博客网 时间:2024/06/05 11:41

Leetcode Best Time to Buy and Sell Stock 相关代码,本题使用dp算法完成,本算应该算得上一个经典的dp算法题。

#include <iostream>#include <vector>using namespace std;// We used a base var save the current smallest, and the max of profite comes from the exist max or// the left element subtract current base element.class Solution {public:    int maxProfit(vector<int>& prices) {        if (prices.size() == 0) {            return 0;        }        int base = prices[0];        int max = 0;        int len = prices.size();        for (int i = 0; i < len; i ++) {            if (prices[i] < base) {                base = prices[i];            } else if (prices[i] - base > max) {                max = prices[i] - base;            }        }        return max;    }};int main(int argc, char* argv[]) {    Solution so;    vector<int> test;    test.push_back(3);    test.push_back(5);    test.push_back(2);    test.push_back(7);    test.push_back(8);    int re = so.maxProfit(test);    cout<<"result is : "<<re<<endl;}
0 0
原创粉丝点击