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.

    Analyse: dp[i] = max(dp[i-1], prices[i] - lowest[0,..., i-1]).

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         const int n = prices.size();
     5         if(n == 0) return 0;
     6         
     7         int dp[n] = {0};
     8         int lowest = prices[0];
     9         for(int i = 1; i < prices.size(); i++){
    10             dp[i] = max(dp[i - 1], prices[i] - lowest);
    11             lowest = min(lowest, prices[i]);
    12         }
    13         return dp[n - 1];
    14     }
    15 };

    or 

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         if(prices.size() <= 1) return 0;
     5         
     6         int result = 0, pre = 0;
     7         int lowest = prices[0];
     8         for(int i = 1; i < prices.size(); i++){
     9             result = max(pre, prices[i] - lowest);
    10             lowest = min(lowest, prices[i]);
    11             pre = result;
    12         }
    13        return result;
    14     }
    15 };
  • 相关阅读:
    哈佛大学官网图标下拉变小代码
    9.23 基础知识
    选项卡效果
    滑动效果
    进度条的制作
    图片轮播
    子菜单下拉
    DIV做下拉列表
    日期时间选择
    电池的基本知识
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4743982.html
Copyright © 2011-2022 走看看