LeetCode brush questions (beginner): The best time to buy and sell stocks II

topic:

You are given an integer array prices, where prices[i] represents the price of a certain stock on day i.

On each day, you can decide whether to buy and/or sell stocks. You can hold at most one share of stock at any one time. You can also buy first and then sell on the same day.

Return the maximum profit you can make.

Problem-solving ideas:

My idea to solve this problem is this, I want to use a greedy algorithm to solve this problem. That is to find the time when the stock rose from the origin, and then find the time point when the stock rose the most, and then subtract the prices of these two time points.

class Solution {
    public int maxProfit(int[] prices) {
            int index = 0;
            int total = 0;
            int length = prices.length-1;
            for(int i = 0;i<length;i++){
                //找到股票上升的起点
                while(index<length&&prices[index]>=prices[index+1]){
                    index++;
                }
                //不断往前找找到增幅最大的地方
                int min = prices[index];
                while(index<length&&prices[index]<=prices[index+1]){
                    index++;
                }
                int max = prices[index];
                total+=(max-min);
            }

        return total;
    }
}

source:

Author: LeetCode
Link: https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2zsx1/
Source: LeetCode
Copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_55229531/article/details/131361959