算法作业HW16:LeetCode121 Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝买阿迪达斯是假的 编辑:程序博客网 时间:2024/06/05 20:19

Description:

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.

 

 

Note:

Example 1:

Input: [7, 1, 5, 3, 6, 4]

Output: 5

 

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]

Output: 0

 

In this case, no transaction is done, i.e. max profit = 0.

 

Solution:

  Analysis and Thinking:

此题目是给定一组表示每一天股票价格的数组,要求我们设计一算法找出我们在哪一天卖出股票,能将我们的收益最大化。我们可以用i表示买入日,j表示卖出日,i与j一开始都不知道。我们通过先固定j来找到相应的i,也就是假设j是已知的(给定的任一天),则i必定是0--j-1的某一天,i通过遍历0--j-1,找到最便宜买入价对应天数获得,找到了一个最大利润。外围的遍历,通过将j设为0--n-1中的一天,获得n个最大的收益,比较得到其中最大的最大收益对应的天数,就是要求的答案。

 

  Steps:

1.判定输入数组长度,若为0,直接返回0

2.初始化i为0,j为i+1

3.初始化maxiumProfit以及profieCounter,用于记录当前最大收益以及当前价格

4.比较price[i]与当前价格大小,priceCounter更新为两者中较小值

5.计算收益,如果收益变大,则更新maxiumProfit的值

6.遍历,直到i到达数组长度

 

Codes:

    class Solution {      public:          int maxProfit(vector<int> &prices) {              if(prices.size()==0)                  return 0;                              int i=0;              int j=i+1;              int maxiumProfit=0;              int priceCounter=prices[i];                          while(i<prices.size()-1){                  j=i+1;                  if(prices[i]<priceCounter)                      priceCounter=prices[i];                  int tmp=prices[j]-priceCounter;                  if(tmp>maxiumProfit)                      maxiumProfit=tmp;                  i++;              }                         return maxiumProfit<0?:0,maxiumProfit;          }      };  



 

Results:


 

原创粉丝点击