zoukankan      html  css  js  c++  java
  • [Leetcode 37] 121 Best Time to Buy and Sell Stock

    Probelm:

    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.

    Analysis:

    There's obviously a O(n^2) algorithm: try every possible trading plan and find the max one. But it's too slow.

    Another method is that, we first compute every profit in two consecutive days, then in this new profit array, we find the max subarray. This is what we need. Since build a profit array is O(n) and find max subarray is also O(n). The total time complexity is O(n).

    Code:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (prices.size() == 0 || prices.size() == 1) return 0;
     7 
     8         vector<int> profit;
     9         
    10         for (int i=1; i<prices.size(); i++) {
    11             profit.push_back( prices[i] - prices[i-1]);
    12         }
    13         
    14         int max = profit[0], cmax = profit[0];
    15         for (int i=1; i<profit.size(); i++) {
    16             if (cmax < 0) {
    17                cmax = profit[i];
    18             } else {
    19                 cmax += profit[i];
    20             }
    21             
    22             if (cmax > max) {
    23                 max = cmax;
    24             }
    25         }
    26         
    27         return max>0? max : 0;
    28     }
    29 };
    View Code

    Attention:

    blabla

  • 相关阅读:
    文件打开的几种访问模式
    数据分析师简介
    python数据处理----常用数据文件的处理
    markdown使用方法介绍
    gdb调试常用方法介绍
    [OPEN CV] 常用视频操作方法
    [转载]C++中四种强制类型转换方式
    python 定时服务模块
    pymysql安装和使用
    VS2019开发Qt程序中文乱码
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096150.html
Copyright © 2011-2022 走看看