제거 방법 : java.lang.OutOfMemoryError (how to remove : java.lang.OutOfMemoryError)


문제 설명

제거 방법 : java.lang.OutOfMemoryError (how to remove : java.lang.OutOfMemoryError)

이 질문을 해결하고 있습니다(아래에 솔루션(dp 포함)에 대해 설명). java.lang.OutOfMemoryError 오류가 발생합니다. dp가 불필요한 계산을 제거한다는 것을 배웠으므로 dp도 적용했지만 왜 이 오류가 발생하여 dp보다 최적화할 수 있습니까? 또는 솔루션이 작은 입력에 대해 실행될 때 내가 뭔가 잘못하고 있습니까?

문제 설명

귀하의 알고리즘은 시장을 예측하는 데 너무 능숙해져서 이제 Wooden Orange Toothpicks Inc.(WOT)의 주가가 얼마인지 알 수 있습니다. 다음 N일 동안 진행됩니다.

매일 WOT 주식 1주를 사거나 소유하고 있는 WOT 주식을 얼마든지 팔거나 거래를 하지 않을 수 있습니다. 최적의 거래 전략으로 얻을 수 있는 최대 이익은 얼마입니까?


참조 솔루션

방법 1:

As mention in the comment, for your dp table, you are using 50000*50000*64 bit memory (long[][]dp), which is around 20 GB, and it is too large for any personal computer.

The problem can be solved in a much easier manner.

For set of n days, assume that in day i, we have the largest price for WOT, so, to make the largest profit, we need to buy WOT from day 0 to day i ‑ 1, and sell all of them in day i. From day i + 1 onward, we can follow the same strategy, which we will result us the maximum profit.

Space complexity for this solution is O(n), and time complexity is O(n log n) if implemented properly.

Pseudo‑code:

class WOT{
    int day;
    int price;
}

WOT[]data = new WOT[n];
//Initialize data here
long[]cost = new long[n];
for(int i = 0; i < n; i++)
    cost[i] = data[i].price + (i > 0 ? cost[i ‑ 1] : 0);

sort data based on price
int startDate = 0;
long result = 0;
for(int i = n ‑ 1; i >= 0; i‑‑){
    if(data[i].day > startDate){
          int numberOfDays = data[i].day ‑ startDate;
          result += numberOfDays*data[i].price ‑ (cost[data[i].day ‑ 1] ‑ cost[startDate ‑ 1])
          startDate = data[i].day + 1;
    }
}
print result;

(by JSONParserPham Trung)

참조 문서

  1. how to remove : java.lang.OutOfMemoryError (CC BY‑SA 2.5/3.0/4.0)

#dynamic-programming #algorithm #java






관련 질문

나머지 숫자의 xor가 0인 부분 집합의 수를 찾습니다. (Find number of subsets, that xor of remaining numbers equals to 0)

재귀 대신 동적 프로그래밍을 사용하여 가장 큰 공통 접미사(자바스크립트) 찾기 (Use dynamic programming instead of recursion to find largest common suffix (javascript))

제거 방법 : java.lang.OutOfMemoryError (how to remove : java.lang.OutOfMemoryError)

가장 효율적인 좌석 배치 (Most efficient seating arrangement)

aglorithm의 복잡성을 가진 춤 (A dance with an aglorithm's complexity)

장애물이 있는 처음부터 끝까지 경로의 수를 계산합니다. (Count the number of paths from start to end with obstacles)

직사각형 필드 내에서 다양한 크기의 직사각형을 효율적으로 배치 (Efficient placement of variable size rectangles within a rectangular field)

기차 또는 버스를 이용할 수 있는 도시 간 최단 경로 DYNAMIC PROGRAMMING (Shortest path between cities that you can use either train or bus DYNAMIC PROGRAMMING)

인덱스가 오름차순으로 정렬되도록 주어진 합계를 갖는 하위 배열의 개수 (Count of sub-arrays with a given sum such that the indices are in ascending order)

2차원 배열의 경로 수 계산(그리드 Traveller) (Count number of paths on 2d-array (grid Traveller))

n개의 볼과 m개의 빈이 주어지고 각 빈이 특정 용량을 가질 때, 몇 개의 조합이 있습니까? (Given n balls and m bins, each bin with a certain capacity, how many combinations are there?)

재귀 호출을 메모할 때 엄청난 효율성 차이 (Drastic efficiency difference when memoizing recursive calls)







코멘트