top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Maximum profit by buying and selling a share at most twice in JAVA

A person buys shares in the morning and sells them in the same day. He can make maximum two transactions of this type in a day. The second transaction must start after the first one has finished, so the actions are: buy, sell, buy sell. You receive the stock prices throughout the day and have to find the maximum profit a trader can make.


Input: int[] price = {4, 28, 11, 9, 7, 30, 75}; Output: 92 Explanation: The 2 transactions are: buy at 4 and sell at 28 and buy at 7 and sell at 75. This translates into: - 4 + 28 – 7 + 75 = 92.


Solution:


1. static int maxProfit(int[] price) { 2. int length = price.length; 3. int[] profit = new int[length]; 4. 5. int maxPrice = price[length - 1]; 6. for (int i = length - 2; i >= 0; i--) { 7. if (price[i] > maxPrice) { 8. maxPrice = price[i]; 9. } 10. profit[i] = Math.max(profit[i + 1], maxPrice - price[i]); 11. } 12. 13. int minPrice = price[0]; 14. for (int i = 1; i < length; i++) { 15. if (price[i] < minPrice) { 16. minPrice = price[i]; 17. } 18. profit[i] = Math.max(profit[i - 1], profit[i] + (price[i] - minPrice)); 19. } 20. return profit[length - 1]; 21. } 22.

4 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page