November 11, 2023

Viiisit [LeetCode] - 122. Best Time to Buy and Sell Stock II

#javascript#ruby

keep learning, keep coding!

Problem - Best Time to Buy and Sell Stock II

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

翻譯蒟蒻

找到在一系列天數中,以買進和賣出股票的方式獲得的最大利潤。
限制是一次只能持有一股,但可以在同一天內先買進再賣出。


Solution - JavaScript

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let maxProfit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1]
}
}
return maxProfit
};

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let maxProfit = 0;
for (let i = 1; i < prices.length; i++) {
maxProfit += Math.max(0, prices[i] - prices[i-1])
}
return maxProfit
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
def max_profit(prices)
max_profit = 0

(1...prices.length).each do |i|
max_profit += [0, prices[i] - prices[i-1]].max
end

max_profit
end

LeetCode 傳送門 - Best Time to Buy and Sell Stock II