




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.
1using System;
2
3public class Solution {
4    public int MaxProfit(int[] prices) {
5        int profit = 0;
6        for (int i = 1; i < prices.Length; i++) {
7            if (prices[i] > prices[i - 1]) {
8                profit += prices[i] - prices[i - 1];
9            }
10        }
11        return profit;
12    }
13
14    public static void Main(string[] args) {
15        Solution sol = new Solution();
16        int[] prices = {7,1,5,3,6,4};
17        Console.WriteLine("Max Profit: " + sol.MaxProfit(prices));
18    }
19}The C# code implements a simple solution using an iteration over the price array, similar to previous examples. Profit is accumulated for each valid transaction leading to an upward price movement.
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
This JavaScript function utilizes a one-pass loop to efficiently check and accumulate incremental price rises, leading to an overall profit calculation.