Best Time to Buy and Sell Stock II
LeetCode: Best Time to Buy and Sell Stock II
Problem:
Say you have an array 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 (ie, buy one and sell one share of the stock multiple times).
However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- Analysis:
From the problem description, we can complete many transcations as we like.
The max profit will be the sum of all positive profit transcations in the input array.
- Code - Java:
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int result = 0;
for (int i = 1; i < len; i++) {
int profit = prices[i] - prices[i - 1];
result += profit > 0 ? profit : 0;
}
return result;
}
}
- Code - C++:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
int result = 0;
for (int i = 1; i < len; i++) {
int profit = prices[i] - prices[i - 1];
result += profit > 0 ? profit : 0;
}
return result;
}
};
- Code - Python:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
pricesLen = len(prices)
result = 0
for i in range(1, pricesLen):
profit = prices[i] - prices[i - 1]
if profit > 0:
result += profit
return result
- Code - C:
int maxProfit(int* prices, int pricesSize) {
int result = 0;
for (int i = 1; i < pricesSize; i++) {
int profit = prices[i] - prices[i - 1];
result += profit > 0 ? profit : 0;
}
return result;
}
Time Complexity: O(N), N is the length of input array
Space Complexity: O(1)