iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 15
0
自我挑戰組

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

LeetCode 122. Best Time to Buy and Sell Stock II

  • 分享至 

  • xImage
  •  

題目

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

題意

給定陣列,代表每天的股價,交易次數不限,最多能賺多少錢?

Example 1:

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

Example 2:

Input: [1,2,3,4,5]
Output: 4

解題想法

只要當天價格比昨天高,就表示有獲利,將獲利加總,就是我們要的答案

Solution

var maxProfit = function (prices) {
  let Profit = 0;
  for (let i = 1; i < prices.length; i++) {
    if (prices[i - 1] < prices[i]) {
      Profit += (prices[i] - prices[i - 1]);
    }
  }
  return Profit;
};

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

尚未有邦友留言

立即登入留言