A complicated solution(c#) , but Why Memory Limit Exceeded?


  • 0
    J

    Why Memory Limit Exceeded? It seems results are correct.

     public class Solution {
        public int MaxProfit(int[] prices) {
       if (prices.Length <= 1)
                    return 0;
                int buyPrice = prices[0];
                int salePrice = 0;
                int j = 1;
                while (j < prices.Length && buyPrice > prices[j] )
                {
                    buyPrice = prices[j];
                    j++;
                    if (j >= prices.Length)
                        break;
                }
                if ( buyPrice == prices[0] && j >= prices.Length)
                    return 0;
                salePrice = buyPrice;
                while (j < prices.Length && salePrice < prices[j])
                {
                    salePrice = prices[j];
                    j++;
                    if (j >= prices.Length)
                        break;
                }
                if (prices.Length - j == 0)
                    return salePrice - buyPrice;
                int[] newPrices = new int[prices.Length - j];
                for (int i = 0; i < newPrices.Length; i++, j++)
                    newPrices[i] = prices[j];
                return salePrice - buyPrice + MaxProfit(newPrices);
            }
        
    }

  • 0
    G

    If the test case only allows you to use constant extra memory, then "newPrices" may be the issue.
    Otherwise, your looping could be incorrect (I say this from my experience, not by reading your code).


Log in to reply
 

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