Leetcode::Best Time to Buy and Sell Stock

从前往后,用当前价格减去此前最低价格,就是在当前点卖出股票能获得的最高利润。
扫描的过程中更新最大利润和最低价格就行了。
O(n)

大数据48ms 过

class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

int min=0x7fffffff;
int max= 0;

for( int i = 0; i < prices.size(); ++i )
{
  int tmp =prices[i];
  if( tmp < min )
  {
    min = tmp;
  }

  if( tmp - min > max )
  {  
    max = tmp - min;
  }
}

  return max;
  }
};

posted @ 2013-05-28 09:08  NinaGood  阅读(94)  评论(0编辑  收藏  举报