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
  • 相关阅读:
    NGINX-HTTPS
    README
    SSH
    Ubuntu
    Python复利
    Python全双工聊天
    Python半双工聊天
    Python网络编程
    使用Python PIL库中的Image.thumbnail函数裁剪图片
    Python模块 os.walk
  • 原文地址:https://www.cnblogs.com/superzrx/p/3355342.html
Copyright © 2011-2022 走看看