*Leetcode 813. Largest Sum of Averages | dp

https://leetcode.com/problems/largest-sum-of-averages/description/
의외로 n^2*kA를 떨어뜨릴 수 있다니...
class Solution {
public:
    double largestSumOfAverages(vector& A, int K) {
        int n = A.size();
        if (n == 0) return 0;
        double sum[n+1];
        for (int i = 0; i < n; i++) {
            sum[i] = i == 0? A[i] : sum[i-1] + A[i];
        }
        if (K >= n) {
            return sum[n-1];
        }

        vector< vector >dp( A.size() + 1 , vector(K+1, 0.0)  );
        
        for (int i = 0; i < n; i++ ) {
            for (int t = 1; t <= K; t++) {
                for (int j = 0; j <= i; j++) { // j         
                    if (t > i+1) continue;
                    if (t == 1 || j == 0 ) {
                        dp[i][t] =   (sum[i]  ) / (i +1);
                        continue;
                    }
                    dp[i][t] = max(dp[i][t], dp[j-1][t-1] + (sum[i] - sum[j-1]) / (i-j+1));
                }
            }
        }
        
        return dp[n-1][K];
    }
};

좋은 웹페이지 즐겨찾기