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)

  • 相关阅读:
    Java.util.concurrent包学习(一) BlockingQueue接口
    [转载]最牛B的编码套路
    思考人生
    非奇异矩阵的零度互补法则
    Hopfield 网络(下)
    Hopfield 网络(上)
    矩阵的相似性与对角化
    左右特征向量
    特征多项式、代数重数与几何重数
    特征值和特征向量
  • 原文地址:https://www.cnblogs.com/forcheryl/p/3978270.html
Copyright © 2011-2022 走看看