现在的位置: 首页 > 综合 > 正文

【LeetCode笔记】Best Time to Buy and Sell Stock II

2018年05月24日 ⁄ 综合 ⁄ 共 372字 ⁄ 字号 评论关闭

这个笔记跟这个题目没有多大关系。这题目是很简单的。code:

int maxProfit(vector<int> &prices) {
    int total = 0;
    int n = prices.size();
    for(int i = 0; i < n - 1; ++i)
        if(prices[i] < prices[i + 1])
            total += prices[i + 1] - prices[i];
    return total;
}

开始时,我是这样写for循环的: for(int i = 0; i < prices.size() - 1; ++i)。结果当prices为空时,程序会报错,觉得很奇怪,不会进入循环呀。

输出 prices.size() - 1,才发现其值为4294967295,就是无符号整形的最大值,也是有符号整形的-1。

换成以上的写法就没错了。这么简单的问题以前是没有遇到过?还是跟编译器有关系?不管啦,以后要注意。

抱歉!评论已关闭.