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
  • 相关阅读:
    设计模式来替代if-else
    Cloneable接口的作用与深度克隆与浅度克隆
    IP地址分类
    MIME-TYPE
    Linux curl
    Cookie 跨域???
    冒烟测试
    @Valid、@Validated 、正则验证工具
    Node.js—第一个动态页面
    Node.js—小试牛刀-创建目录
  • 原文地址:https://www.cnblogs.com/superzrx/p/3355342.html
Copyright © 2011-2022 走看看