Maximum return on stock trading

Question source

Maximum return on stock trading

Title description

Suppose you know the daily price changes of a certain stock.
You can hold at most one stock at the same time. But you can trade unlimited times (no commission for buying and selling).
Please design a function to calculate the maximum benefit you can get.
Insert picture description here
Insert picture description here

answer

import java.util.*;
public class Solution {
    
    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
    
    
        int start=0;
        int max=0;
        for(int i=1;i<prices.length;i++){
    
    
            if(prices[i]<prices[i-1]){
    
    
                max=max+(prices[i-1]-prices[start]);
                start=i;
            }
        }
        return max+prices[prices.length-1]-prices[start];
    }
}

Guess you like

Origin blog.csdn.net/qq_44929652/article/details/109014457