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.

    vector下标,初始化

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if(prices.size() == 0)return 0;
            int s = prices.size();
            vector<int> min(s,prices[0]);
            vector<int> max(prices.size(),prices[prices.size()-1]);
            
            //min.push_back(prices[0]);
            for(int i = 1 ; i < s ; i++) 
            if(min[i - 1] > prices[i]) min[i] = prices[i];
            else min[i] = min[i-1];
            
            //max.push_back(prices[s-1]);
            for(int j = s-2 ; j >= 0 ; j --)
            if(prices[j] > max[j+1]) max[j] = prices[j];
            else max[j] = max[j+1];
            
            int pro = 0 ;
            for(int i = 0 ; i < s ;i++)if(pro < max[i] - min[i]) pro = max[i] - min[i];
            return pro;
        }
    };
    

      更简单的方法:

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function 
            if (prices.size() == 0) {
                return 0;
            }
            int min = prices[0], profit = 0;
            for (int i = 1; i < prices.size(); i++) {
                profit = prices[i] - min > profit ? prices[i] - min : profit;
                min = prices[i] < min ? prices[i] : min;
            }
            return profit;
        }
    };
    

      空间上更优

  • 相关阅读:
    Python 30分钟入门——数据类型 &amp; 控制结构
    POJ 3101 Astronomy
    Java8 Lamdba表达式 001
    浅谈PPM (Project Portfolio Management)
    char* 和char[]的差别
    福州大学第十一届程序设计竞赛
    用 Python 测试框架简化测试
    15个最受欢迎的Python开源框架
    python测试框架总结
    python测试框架--nose
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3580404.html
Copyright © 2011-2022 走看看