Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
Get Maximum Subarray with the array

I want to do a variation of the get Maximum subarray from leetcode in which I collect the entire maximum subarray as well, but I can't seem to figure out what I'm missing.

var maxSubArray = function(nums) {
    let currSum = 0;
    let maxSum = -Infinity;
    let currArray = [];
    let maxArray = [];

    for (let i = 0; i < nums.length; i++) {
        currSum += nums[i];

        if (Math.max(currSum, maxSum) != maxSum) {
            maxArray = currArray;
            maxSum = currSum;
            currArray.push(nums[i]);
        }
    

        maxSum = Math.max(currSum, maxSum);
    
        if (currSum < 0) {
            currSum = 0;
            currArray = []
        }
    
    }
    console.log(maxArray);

    return maxSum;
};

I recognize why this is wrong, as the currSum value cannot have a negative component because it'd always be a lower sum than the current maxSum. But I'm not sure what condition it would require for this. I feel like I'm missing something obvious but cannot think of it :(

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I was going about it the wrong way as I was storing an array when I could have just stored the index.

var maxSubArray = function(nums) {
    let currSum = 0;
    let maxSum = -Infinity;
    let prevMax = -Infinity;
    let start = 0;
    let end = 0;
    for (let i = 0; i < nums.length; i++) {
        currSum += nums[i];
        
        if (nums[i] > maxSum) {
            start = i;
        }
        
        if (Math.max(currSum, maxSum) != maxSum) {
            maxSum = currSum;
            end = i;
        }
    
        if (currSum < 0) {
            currSum = 0;
            if (nums[i+1] != undefined) {
                start = i+1;
            }
        }
        
    }
    console.log(start, end);
    console.log(nums.slice(start, end+1))
    
    return maxSum;
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda