Level:easy
Topic: Array、Dynamic Programming
Description
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
拿到一個prices array prices[i]代表 i天的股票,我們需要寫一隻程式來選擇一天購買股票選擇另一天賣掉股票最大化收益 return 最大化收益,如果達不到return 0
Example
const prices = [7, 1, 5, 3, 6, 4] // should return 5 // buy at day 1, sell at day 2
Solution
宣告2個變數分別是low(代表最低買入價格)、max(代表最高的收益),股市開盤的價格就是最低價格因為沒有前面的價格, 因此low初始化為prices[0],接著從第2天開始去計算收益也就是prices[i] - low,計算出來的結果若是比當前 最大收益還多更新最大收益max = prices[i] - low,否的話則代表當前的low可能不是最低所以需要比較low與當天價格, 當天價格小於low則更新low。
/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let max = 0; let low = prices[0]; for (let i = 1; i < prices.length; i++) { profit = prices[i] - low if (profit > max) { max = profit } else { if (prices[i] < low) low = prices[i] } } return max };
Best Solution(Gemini提供)
/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let max = 0; let low = prices[0]; for (let i = 1; i < prices.length; i++) { max = Math.max(max, prices[i] - low) low = Math.min(low, prices[i]) } return max };