zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock II--疑惑

    https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

    代码如下时能AC

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

    但是,代码如下时却Runtime Error,提示Last executed input:[]

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

    这代码明明跟这段Java是一样的啊。这Java代码也能AC。奇怪。

    1 public class Solution {
    2 public int maxProfit(int[] prices) {
    3     int total = 0;
    4     for (int i=0; i< prices.length-1; i++) {
    5         if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i];
    6     }
    7 
    8     return total;
    9 }

     最后只能是加入一行

    1  if(prices.size()==0) return 0;

    来保证edge case.

    ——————————————————————————————————————————————————————————————————————

    This problem is solved by Shangrila finally:

    Replace prices.size()-1 by int(prices.size())-1. The type of prices.size() is SIZE_T, which is unsigned integer types. -1 could overflow.

    answered 9 hours ago by Shangrila (48,010 points)

  • 相关阅读:
    webpack学习最基本的使用方式(一)
    exports default 和export的使用方式
    vue兄弟组件之间的传值方式
    vue组件之间的传值方式
    vue组件创建学习总结
    vue实例生命周期钩子
    this 的工作原理
    node版本升级参考
    ES6 promise学习
    弹性布局学习总结
  • 原文地址:https://www.cnblogs.com/forcheryl/p/3978270.html
Copyright © 2011-2022 走看看