_122买卖股票的最佳时机II_贪心
原题链接:
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/submissions/540259916/
完成情况:
解题思路:
Sure! The given Java code solves the “Best Time to Buy and Sell Stock II” problem using a greedy algorithm. Let’s go through the code step-by-step:
Problem Description
The problem requires you to find the maximum profit from buying and selling a stock given its prices over several days. You can buy and sell multiple times, but you can only hold one share of the stock at a time.
Code Explanation
-
Method Signature:
public int maxProfit(int[] prices) {
This is the method
maxProfit
which takes an array of integersprices
as input and returns an integer representing the maximum profit. -
Initialization:
int result = 0;
Here,
result
is initialized to store the cumulative profit. -
Greedy Algorithm:
for (int i = 1; i < prices.length; i++) { result += Math.max(0, prices[i] - prices[i-1]); }
This loop iterates over the
prices
array starting from the second day (index 1) to the last day. For each dayi
, it calculates the profit made by buying the stock on dayi-1
and selling it on dayi
:prices[i] - prices[i-1]
represents the profit if the stock is bought on dayi-1
and sold on dayi
.Math.max(0, prices[i] - prices[i-1])
ensures that only positive profits are added toresult
. If the difference is negative (meaning selling at a loss), it adds 0 instead.
The greedy approach works because the problem allows for multiple transactions, even on the same day. By always taking advantage of every increase in stock price, we can ensure that the total profit is maximized.
-
Return Result:
return result;
Finally, the method returns the accumulated profit stored in
result
.
Summary
The greedy algorithm used here is straightforward and efficient. It iterates through the price array once (O(n) time complexity), adding up all the positive differences between consecutive days. This ensures that every possible profit opportunity is taken, leading to the maximum profit by the end of the period. This approach is optimal for this problem because it takes advantage of every price increase without worrying about the specifics of when to buy and sell.
参考代码:
_122买卖股票的最佳时机II_贪心
package leetcode板块;
public class _122买卖股票的最佳时机II_贪心 {
/**
*
* @param prices
* @return
*/
public int maxProfit(int[] prices) {
// 这道题由于说了可以同一天卖出买入,因此只需要考虑是否能够赚到钱,即可以
int result = 0;
for (int i = 1;i<prices.length;i++){
result += Math.max(0,prices[i] - prices[i-1]);
}
return result;
}
}