码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock

时间:2015-06-30 10:42:30      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:
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.
解决方案:
动态规划解法:
profit[i]数组表示在第i天卖出获得的最大利润。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
      if(prices.empty())
      {
          return 0;
      }
      int* profit = new int[prices.size()];
      profit[0] = 0;
      int maxx = profit[0];
      for(int i = 1;i<prices.size();i++)
      {

          if(prices[i]>=prices[i-1])
          {
              profit[i] = profit[i-1]+ prices[i] - prices[i-1];
          }else{
               if(prices[i-1]-profit[i-1]<prices[i])
                profit[i] = prices[i] - prices[i-1]+profit[i-1];
                else{
                    profit[i] =0;
                }
          }
          if(profit[i]>min)
            maxx = profit[i];
      }
      return maxx;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

Best Time to Buy and Sell Stock

标签:

原文地址:http://blog.csdn.net/leosha/article/details/46687431

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!