zoukankan      html  css  js  c++  java
  • [LeetCode] Best Time to Buy and Sell Stock Solution


    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.
    » Solve this problem

    [Thoughts]
    Scan from left to right. And keep track the minimal price in left. So, each step, only calculate the difference between current price and minimal price.
    If this diff large than the current max difference, replace it.


    [Code]
    1:    int maxProfit(vector<int> &prices) {  
    2: // Start typing your C/C++ solution below
    3: // DO NOT write int main() function
    4: int minV=INT_MAX; int max =0;
    5: int diff=0;
    6: for(int i =0; i< prices.size(); i++)
    7: {
    8: if(prices[i]<minV) minV = prices[i];
    9: diff = prices[i] - minV;
    10: if(max<diff)
    11: max = diff;
    12: }
    13: return max;
    14: }


  • 相关阅读:
    java面向对象day01
    找工作——JVM内存管理
    找工作——多线程
    找工作-——网络IO
    找工作--volatile
    找工作——异常处理
    找工作--设计模式
    Sqoop安装
    NIO
    Hadoop源码编译
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078930.html
Copyright © 2011-2022 走看看