Untitled
unknown
plain_text
5 months ago
2.6 kB
3
Indexable
public class CurrencyTradingOptimization { public static int optimizedSolution(int[] rates, int[] strategy, int k) { int n = strategy.length; // Initial profit calculation int initialProfit = 0; for (int i = 0; i < n; i++) { if (strategy[i] == -1) { initialProfit -= rates[i]; // Buying, subtract the rate } else if (strategy[i] == 1) { initialProfit += rates[i]; // Selling, add the rate } } int maxProfit = initialProfit; int currentProfit = initialProfit; // Iterate through all possible ranges of length k for (int i = 0; i <= n - k; i++) { // Backup original values in the range int[] originalValues = new int[k]; System.arraycopy(strategy, i, originalValues, 0, k); // Calculate the profit change when modifying the current range int profitChange = 0; // Remove the effect of original values in the first half for (int j = 0; j < k / 2; j++) { if (originalValues[j] == -1) { profitChange += rates[i + j]; // Undo buying, add back the rate } else if (originalValues[j] == 1) { profitChange -= rates[i + j]; // Undo selling, subtract the rate } } // Remove the effect of original values in the second half for (int j = k / 2; j < k; j++) { if (originalValues[j] == -1) { profitChange += rates[i + j]; // Undo buying, add back the rate } else if (originalValues[j] == 1) { profitChange -= rates[i + j]; // Undo selling, subtract the rate } } // Add the effect of new values (setting to 1) in the second half for (int j = k / 2; j < k; j++) { profitChange += rates[i + j]; // Selling, add the rate } // Update the current profit based on the change currentProfit = initialProfit + profitChange; maxProfit = Math.max(maxProfit, currentProfit); } return maxProfit; } public static void main(String[] args) { int[] rates = {2, 4, 1, 5, 10, 6}; int[] strategy = {-1, 1, 0, 1, -1, 0}; int k = 4; // Run the optimized solution function on the provided test case int result = optimizedSolution(rates, strategy, k); System.out.println(result); // Expected output: 18 } }
Editor is loading...
Leave a Comment