




Sponsored
Sponsored
The Peak-Valley Approach aims to identify opportunities where a buy (at a valley) and a sell (at a peak) transaction yields profit. The idea is to take advantage of every upward trend between valleys and peaks and sum up the differences.
Time Complexity: O(n), where n is the number of prices. 
Space Complexity: O(1), no additional space is used.
1function maxProfit(prices) {
2    let profit = 0;
3    for (let i = 1; i < prices.length; i++) {
4        if (prices[i] > prices[i - 1]) {
5            profit += prices[i] - prices[i - 1];
6        }
7    }
8    return profit;
9}
10
11const prices = [7, 1, 5, 3, 6, 4];
12console.log("Max Profit:", maxProfit(prices));This JavaScript code also loops over the prices array, checking where the next day's price is higher than the current, and adds that difference to the total profit. This ensures maximum gain from every small spike.
The simple one-pass greedy approach makes a decision on each day based on whether the price will go up (buy or hold) or down (sell or do nothing). This maximizes profit by keeping solutions simple, efficient and using the greedy approach to sum up all local gains.
Time Complexity: O(n) 
Space Complexity: O(1)
1
public class Solution {
    public int MaxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.Length; i++) {
            profit += (prices[i] > prices[i - 1]) ? prices[i] - prices[i - 1] : 0;
        }
        return profit;
    }
    public static void Main(string[] args) {
        Solution sol = new Solution();
        int[] prices = {7,1,5,3,6,4};
        Console.WriteLine("Max Profit: " + sol.MaxProfit(prices));
    }
}The C# implementation closely follows the logic laid out in the approach description: iterating through price data once, summing positive differentials.