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;
        }
    };
    

      空间上更优

  • 相关阅读:
    Linux系统root密码修改
    网络通信
    运维平台cmdb开发-day1
    questions information
    Django Rest Framework
    Django-CBV和跨域请求伪造
    Flask学习
    会议室预定终章
    python的可变数据类型和不可变类型
    模拟admin组件自己开发stark组件之搜索和批量操作
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3580404.html
Copyright © 2011-2022 走看看