How is this possible?

  • 0

    How is it possible that the max profit is 2?

    Here is my code -

    public class Solution {
    public int maxProfit(int[] prices) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (prices.length == 0 ) return 0;
        int min = prices[0];
        int max = 0;
        for (int i = 1; i<prices.length;i++){
            if (prices[i] < min)
                min = prices[i];
            int diff = prices[i] - min;
            if (diff > max){
                max = diff;
        return max;


  • 0

    The algorithm looks right, at first glance. Do you happen to have the input that gave your result?

  • 0

    Looking back at this code, I actually did spot an error. What you are returning is the maximum profit for a single transaction, not multiple as allowed in problem II. Problem I is the single transaction problem.

  • 0

    that's right, he return the max profit of a single transaction

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.