zoukankan      html  css  js  c++  java
  • LeetCode OJ: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.

    简单的DP问题,可是一开始我没读懂题目的意思。这里的买入当然应该在卖出之前,所以说不是那种取一个max一个min相减就能解决的,代码如下:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         int sz = prices.size();
     5         if(sz == 0 || sz == 1) return 0;
     6         int min, maxGain;
     7         min = prices[0];//min的初值要注意
     8         maxGain = 0;
     9         for(int i = 0 ; i < sz; ++i){
    10             if(min > prices[i])
    11                 min = prices[i];
    12             else if(maxGain < prices[i] - min)
    13                 maxGain = prices[i] - min;
    14         }
    15         return maxGain;
    16     }
    17 };

     下面是java写的,runtime还行,击败了60%的runtime,方法和上面有一点不同,如下:

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         int maxVal = 0;
     4         int start = 0;
     5         for(int i = 1; i < prices.length; ++i){
     6             if(prices[i] < prices[i-1]){
     7                 maxVal = Math.max(prices[i-1]-prices[start], maxVal);
     8                 if(prices[i] < prices[start])
     9                     start = i;
    10             }
    11         }
    12         if(prices.length != 0)//排除长度是0的情况
    13             maxVal = Math.max(prices[prices.length - 1] - prices[start], maxVal);   //防止出现一直到结尾都不断增大的问题
    14         return maxVal;    
    15     }
    16 }
  • 相关阅读:
    Python
    Python
    Python
    Python
    Python
    《The Rise and Fall of Scala》scala的兴衰
    Scala核心编程_第05章_函数式编程
    IntelliJ IDEA scala的源码设置
    Scala核心编程_第04章 程序流程控制
    Scala核心编程_第03章_运算符
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4878996.html
Copyright © 2011-2022 走看看