Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- /**
- * Calculates the maximum profit from stock trading with the constraint of
- * holding at most one share of stock at a time, but allows buying and selling
- * on the same day.
- *
- * @param prices Array of stock prices where prices[i] is the price of the stock on the ith day.
- * @return The maximum profit that can be achieved.
- *
- * Time Complexity: O(n), where n is the length of the prices array.
- * This is because we need to traverse the entire array once.
- * Space Complexity: O(1), as the solution requires a constant amount of space
- * for the variables used, regardless of the input size.
- */
- private static int maxProfit(int[] stockPrices) {
- if (stockPrices == null || stockPrices.length <= 1) {
- return 0;
- }
- var maxProfit = 0;
- for (var i = 1; i < stockPrices.length; i++) {
- if (stockPrices[i] > stockPrices[i - 1]) {
- maxProfit += stockPrices[i] - stockPrices[i - 1];
- }
- }
- return maxProfit;
- }
- public static void main(String[] args) {
- var stockPricesT1 = new int[] {7, 1, 5, 3, 6, 4};
- System.out.println("Maximum profit: " + maxProfit(stockPricesT1));
- var stockPricesT2 = new int[] {1, 2, 3, 4, 5};
- System.out.println("Maximum profit for example 2: " + maxProfit(stockPricesT2));
- var stockPricesT3 = new int[] {7, 6, 4, 3, 1};
- System.out.println("Maximum profit for example 3: " + maxProfit(stockPricesT3));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement