您的位置:首页 > 其它

[Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机

2017-06-29 16:54 561 查看

Say you have an array for which the i th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 题意:可以做多次交易,但必须是做完一次交易了,再做下一次。

思路:这个要注意和显示生活中区别,这里是每天股票的价格已经知道了,所以,买卖的时候,只要是盈利的都做。大致过程是,对相邻两天的股票价格比较,只要后者大于前者,这次买卖就做。代码如下:

1 class Solution {
2 public:
3     int maxProfit(vector<int> &prices)
4     {
5         int profit=0;
6         int len=prices.size();
7         for(int i=0;i<len-1;++i)
8         {
9             if(prices[i+1]-prices[i]>0)
10                 profit+=prices[i+1]-prices[i];
11         }
12         return profit;
13     }
14 };

这里值得注意的是:若代码中第6、7两行写成如下形式,是不能AC的。个人认为是prices.size()的类型为vector<int>::size_type,而减1以后,在prices.size()=0的情况,会负溢出。导致i小于一个正整数,但是数组中没有值,对数组进行访问时,会发生段问题。

(自己的考虑,没有考虑到类型限制,详情见下面)

1 for(int i=0;i<prices.size()-1;++i)
2 {
3     ......
4 }

在本地验证的代码:

1 #include<iostream>
2 #include<vector>
3
4 using namespace std;
5
6 int main()
7 {
8     vector<int> a ;
9     cout << a.size() - 1 << endl;
10     return 0;
11 }
12
13 //输出42949647295

解决的方法:一、之前加if判断,二、使用最上面代码中的那种方式--先求数组大小,然后用这个值去参与for循环。

//更新

这里给出Grandyang的回答:因为prices.size()返回的是size_type型的,这是一种unsigned类型,也就是无符号类型,所以在直接对其做减法是不行的,因为负数对其来说不合法,所以我们可以先强制将其转为整型,再做法,比如:

1 for(int i = 0; i < (int)prices.size() - 1; ++i)
2 {
3     ......
4 }

(感谢Grandyang!!!)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐