




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.
1public class Solution {
2    public int maxProfit(int[] prices) {
3        int profit = 0;
4        for (int i = 1; i < prices.length; i++) {
5            if (prices[i] > prices[i - 1]) {
6                profit += prices[i] - prices[i - 1];
7            }
8        }
9        return profit;
10    }
11
12    public static void main(String[] args) {
13        Solution sol = new Solution();
14        int[] prices = {7,1,5,3,6,4};
15        System.out.println("Max Profit: " + sol.maxProfit(prices));
16    }
17}This Java solution also iterates through the prices array, capturing every opportunity to profit from upward movements. The profits are summed up to give the final answer.
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#include <iostream>
int maxProfit(std::vector<int>& prices) {
    int profit = 0;
    for (size_t i = 1; i < prices.size(); ++i) {
        profit += (prices[i] > prices[i - 1]) ? prices[i] - prices[i - 1] : 0;
    }
    return profit;
}
int main() {
    std::vector<int> prices = {7,1,5,3,6,4};
    std::cout << "Max Profit: " << maxProfit(prices) << std::endl;
    return 0;
}Using C++, the strategy is also greedy, where the solution boils down to adding up small profitable differences found between consecutive days of price increases.