leetcode Question 49: Maximum subarray

Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.


Analysis:
Classic DP problem.

We can think this problem as this: if the previous sum are +, which is then useful for the current element, or if it is -, why not start the sub array from current element? We can use an int to store the max sum we have got, just scan the whole array, the result is easily found.

Source Code:

class Solution {
public:
    int maxSubArray(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int m=INT_MIN;
        int sum=0;
        for (int i=0;i<n;i++){
            sum = sum>=0?(sum+A[i]):A[i];
            m=max(sum,m);
        }
        return m;
    }
};

1 comment:


  1. 1

    Sort the toys according to price and keep taking toys as long as you have money left.

    // Complete the maximumToys function below.
    function maximumToys(prices, k) {
    var bought = 0
    var pricings = prices.sort((a, b) => a - b)
    var amtLeft = k;
    for (var i = 0; i < pricings.length; i++){
    if (amtLeft < pricings[i]) {
    break;
    } else {
    amtLeft = amtLeft - pricings[i];
    bought++;
    }
    }
    return bought
    }

    https://judocoder.com/try/challenge/Maximum-toys-to-buy

    ReplyDelete