LeetCode编程练习 - Best Time to Buy and Sell Stock学习心得

题目:

      Say you have an array for which theith 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.

      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.

     求进行一次交易(一次买入和卖出)得到的最大利润。假设有一个数组,第i个元素是给定股票的价格。


思路:

   不考虑其他因素的情况下利润等于成交价减去给定的价格,售价价格要大于给定的价格,只要将成交价减去股票价格然后一一作比较取最大值即可,但题目中没有涉及成交价。从给出的示例来看,代码要实现的是在数组中,后者大于前者的情况下进行减法运算,若没有满足,则输出为0,而且对差做比较,输出最大的那个。刚开始我直接对前后判断数值大小,显示“超出索引值大小”。

    我的程序以及更改后的程序:

LeetCode编程练习 - Best Time to Buy and Sell Stock学习心得LeetCode编程练习 - Best Time to Buy and Sell Stock学习心得

    

    对比解决方案,思路上并无太大差异,但有一点需要注意,虽然运行没有错误,但是由于条件为后者大于前者,因此前者的取值范围应该是prices.Length-1。解决方案中是判断差值大小后,若差值大于前一项的差值,则赋值

    解决方案:

LeetCode编程练习 - Best Time to Buy and Sell Stock学习心得