Problem Statement:
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.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
Constraints
1 <= prices.length <= 3 * 1040 <= prices[i] <= 104
Approach:
- If the price today is higher than yesterday, we add the profit
(prices[i] - prices[i-1])to our total. - Otherwise, we skip (no loss is counted). This way, we sum all upward moves to get the maximum profit.
Time & Space Complexity:
Time Complexity: O(n)
Space Complexity: O(1)
Dry Run
Input: prices = [7, 1, 5, 3, 6, 4]
Step 1: Initialize ans = 0 Step 2: Iterate over prices i = 1 → profit = prices[1] - prices[0] = 1 - 7 = -6 profit ≤ 0 → no change → ans = 0 i = 2 → profit = prices[2] - prices[1] = 5 - 1 = 4 profit > 0 → ans = 0 + 4 = 4 i = 3 → profit = prices[3] - prices[2] = 3 - 5 = -2 profit ≤ 0 → no change → ans = 4 i = 4 → profit = prices[4] - prices[3] = 6 - 3 = 3 profit > 0 → ans = 4 + 3 = 7 i = 5 → profit = prices[5] - prices[4] = 4 - 6 = -2 profit ≤ 0 → no change → ans = 7 Step 3: End Return ans = 7
Output: Result: 7
var maxProfit = function(prices) {
let ans = 0;
for(let i=1; i 0){
ans += profit;
}
}
return ans;
};
def maxProfit(prices):
ans = 0
for i in range(1, len(prices)):
profit = prices[i] - prices[i - 1]
if profit > 0:
ans += profit
return ans
class Solution {
public int maxProfit(int[] prices) {
int ans = 0;
for (int i = 1; i < prices.length; i++) {
int profit = prices[i] - prices[i - 1];
if (profit > 0) {
ans += profit;
}
}
return ans;
}
}
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector& prices) {
int ans = 0;
for (int i = 1; i < prices.size(); i++) {
int profit = prices[i] - prices[i - 1];
if (profit > 0) {
ans += profit;
}
}
return ans;
}
};
#include <stdbool.h>
int maxProfit(int* prices, int pricesSize) {
int ans = 0;
for (int i = 1; i < pricesSize; i++) {
int profit = prices[i] - prices[i - 1];
if (profit > 0) {
ans += profit;
}
}
return ans;
}
public class Solution {
public int MaxProfit(int[] prices) {
int ans = 0;
for (int i = 1; i < prices.Length; i++) {
int profit = prices[i] - prices[i - 1];
if (profit > 0) {
ans += profit;
}
}
return ans;
}
}
