---
# System prepended metadata

title: \#121 Best Time to Buy and Sell Stock
tags: [leetcode, leetcode-easy]

---

# \#121 Best Time to Buy and Sell Stock
## *給定一陣列, 回傳該陣列任兩元素的最大差:MAX(後元素-前元素)*
## Log
 - build 20210529 by syhuang

## 最大子數列問題(Kadane's Algorithm)
```javascript=
var maxProfit = function(prices) {
    if(prices.length<2) return 0;
    var diff = 0;
    var maxDiff = 0;
    for(var i=1; i<prices.length; i++){
        diff = Math.max(0,diff += prices[i]-prices[i-1]);
        maxDiff = Math.max(maxDiff,diff);
    }
    return maxDiff;
};
```
## 備註
 - 沒解出來, 在此先記錄演算法:最大子數列問題(Kadane's Algorithm)
## 參考
 - [參考解](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/39038/Kadane's-Algorithm-Since-no-one-has-mentioned-about-this-so-far-%3A\)-(In-case-if-interviewer-twists-the-input))
###### tags: `leetcode`, `leetcode-easy`