1. Split Point Enumeration with O(n^2) Check
Intuition
Iterate over every possible split day i (from 0 to n-1). Find the max profit for one transaction in [0..i] and one transaction in [i..n-1].
Algorithm
- For each index
ifrom 0 to n-1: - Calculate max profit for single transaction in
prices[0..i]. - Calculate max profit for single transaction in
prices[i..n-1]. - Add both profits and update
maxTotal. - Return
maxTotal.
Split Point Enumeration (O(N^2))
2 of 2 questions left todaySum of two non-overlapping transactions: 2 + 4 = 6
Sum of two non-overlapping transactions: 2 + 4 = 6.
#include <iostream>#include <vector>#include <algorithm> using namespace std; int maxProfitBrute(const vector<int>& prices) { int n = prices.size(); if (n <= 1) return 0; int maxTotal = 0; for (int i = 0; i < n; i++) { // First transaction [0..i] int minP = prices[0], p1 = 0; for (int j = 0; j <= i; j++) { minP = min(minP, prices[j]); p1 = max(p1, prices[j] - minP); } // Second transaction [i..n-1] int minP2 = prices[i], p2 = 0; for (int j = i; j < n; j++) { minP2 = min(minP2, prices[j]); p2 = max(p2, prices[j] - minP2); } maxTotal = max(maxTotal, p1 + p2); } return maxTotal;} int main() { vector<int> prices = {3, 3, 5, 0, 0, 3, 1, 4}; cout << "Max Profit (Brute Force): " << maxProfitBrute(prices) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(n^2) - Space complexity:
O(1)