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

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

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    算法导论原题,股票买入卖出的最大利益-->数组中后面的元素与前面的元素的最大差值-->转换为连续子数组最大和

    class Solution {
    public:
        int maxProfit(vector<int>& diff,int diffSize){
            int curMax=0;
            int res = 0;
            for(int i=0;i<diffSize;i++){
                if(i==0){
                    curMax = diff[i];
                    res = diff[i];
                }else{
                    curMax = max(curMax+diff[i],diff[i]);
                    res = max(res,curMax);
                }
            }
            return res;
        }
        int maxProfit(vector<int>& prices) {
            int pricesSize = prices.size();
            vector<int> diff(pricesSize,0);
            for(int i=1;i<pricesSize;i++){
                diff[i] = prices[i]-prices[i-1];
            }
            return maxProfit(diff,pricesSize);
        }
    };
  • 相关阅读:
    全文本的检索
    网卡配置
    linux解压命令
    Session
    swoole安装
    Linux 系统磁盘满处理方法
    php写入和读取文件内容
    PHP读取文件夹的文件列表
    php 公历农历互相转换
    PHP实现RESTful风格的API实例
  • 原文地址:https://www.cnblogs.com/zengzy/p/5004465.html
Copyright © 2011-2022 走看看