iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
0
自我挑戰組

用LeetCode來訓練大腦的邏輯思維系列 第 14

LeetCode 121. Best Time to Buy and Sell Stock

  • 分享至 

  • xImage
  •  

題目

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

題意

給定陣列,代表每天的股價,在只能有一次交易的條件下,最多能賺多少錢?

Example 1:

Input: [7,1,5,3,6,4]
Output: 5

Example 2:

Input: [7,6,4,3,1]
Output: 0

解題想法

先設定最大獲利與最低價格,再依序比較陣列的每個值,每次的迴圈,都會找出目前的最大獲利與最低價格。

Solution

var maxProfit = function (prices) {
  let maxProfit = 0;
  let minPrice = prices[0];
  for (let i = 1; i < prices.length; i++) {
    minPrice = minPrice < prices[i] ? minPrice : prices[i];
    maxProfit = prices[i] - minPrice > maxProfit ? prices[i] - minPrice : maxProfit;
  }
  return maxProfit;
};

上一篇
LeetCode 118. Pascal's Triangle
下一篇
LeetCode 122. Best Time to Buy and Sell Stock II
系列文
用LeetCode來訓練大腦的邏輯思維30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言