Lintcode 149. Best Time to Buy and Sell Stock

題目鏈接: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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章