題目鏈接:https://www.lintcode.com/problem/best-time-to-buy-and-sell-stock/description
有點慚愧,這個代碼我本地測了幾組用例應該是沒問題的,但是OJ報了WA,先貼一下代碼吧。
const INT_MAX = int(^uint(0) >> 1);
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
func maxProfit (prices []int) int {
// write your code here
if (prices == nil || len(prices) == 0) {
return 0;
}
var min int = INT_MAX;
var i, profit int;
profit = 0;
for i = 0; i < len(prices); i++ {
if min > prices[i] {
min = prices[i];
}
if profit < (prices[i] - min) {
profit = prices[i] - min;
}
}
return profit;
}
func main() {
var prices1 = []int{3, 2, 3, 1, 2};
var profit1 int = maxProfit(prices1);
fmt.Println(profit1);
}