• 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
  • 相关阅读:
    18软工实践-第三次作业-结对项目1
    结对作业之代码规范
    ALPHA(7)
    ALPHA(6)
    ALPHA(五)
    404 Note Found 现场编程
    ALPHA(四)
    ALPHA冲刺(三)
    ALpha冲刺(二)
    ALPHA 冲刺(一)
  • 原文地址:https://www.cnblogs.com/superzrx/p/3355342.html
Copyright © 2020-2023  润新知