zoukankan      html  css  js  c++  java
  • LeetCode-Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    每天都可以买或卖,最多持有1股

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            vector<int> best;
            vector<int> next;
            best.resize(2);
            next.resize(2);
            if(prices.size()==0)return 0;
            best[0]=0;
            best[1]=-prices[0];
            next[0]=best[0];
            next[1]=best[1];
            for(int i=1;i<prices.size();i++){
                if(best[0]-prices[i]>next[1])next[1]=best[0]-prices[i];
                if(best[1]+prices[i]>next[0])next[0]=best[1]+prices[i];
                best[0]=next[0];
                best[1]=next[1];
            }
            return max(best[0],best[1]);
        }
    };
    View Code
  • 相关阅读:
    Aviator
    Docker是什么
    vulnhub--SickOs1.1
    vulnhub--HackInOS
    本地浏览器远程访问服务器tensorboard(MobaXterm)
    dogecoin
    python多进程
    gpu
    python调用父类(超类)
    linux更改终端显示颜色(用户名颜色等)
  • 原文地址:https://www.cnblogs.com/superzrx/p/3355342.html
Copyright © 2011-2022 走看看