Get max profit and loss

  • Time Complexity: O(N)

  • Description:

    • series: 价格变动序列

    • pos1: 买入位置

    • pos2: 卖出位置

    • returns: 最大盈利或者亏损

public static double GetMaxProfit(double[] series, out int pos1, out int pos2)
{
    double max_profit = 0;
    double profit = 0;
    int pos = 0;

    pos1 = -1;
    pos2 = -1;

    for (int i = 0; i < series.Length; i++) {
        profit += series[i];
        if (profit < 0) {
            profit = 0;
            pos = i;
        }
        else if (profit > max_profit) {
            max_profit = profit;
            pos1 = pos;
            pos2 = i;
        }
    }
    return max_profit;
}
public static double GetMaxLoss(double[] series, out int pos1, out int pos2)
{
    double max_loss = 0;
    double profit = 0;
    int pos = 0;

    pos1 = -1;
    pos2 = -1;

    for (int i = 0; i < series.Length; i++) {
        profit += series[i];

        if (profit > 0) {
            profit = 0;
            pos = i;
        }
        else if (profit < max_loss) {
            max_loss = profit;
            pos1 = pos;
            pos2 = i;
        }
    }
    return max_loss;
}