@@ -58,22 +58,50 @@ It can be shown that the maximum profit you can make is 0.
58
58
59
59
<!-- 这里可写通用的实现逻辑 -->
60
60
61
+ ** 方法一:动态规划**
62
+
63
+ $0-1$ 背包问题。
64
+
61
65
<!-- tabs:start -->
62
66
63
67
### ** Python3**
64
68
65
69
<!-- 这里可写当前语言的特殊实现逻辑 -->
66
70
67
71
``` python
68
-
72
+ class Solution :
73
+ def maximumProfit (self , present : List[int ], future : List[int ], budget : int ) -> int :
74
+ arr = [(a, b - a) for a, b in zip (present, future) if b > a]
75
+ dp = [0 ] * (budget + 1 )
76
+ for v, w in arr:
77
+ for j in range (budget, v - 1 , - 1 ):
78
+ dp[j] = max (dp[j], dp[j - v] + w)
79
+ return dp[- 1 ]
69
80
```
70
81
71
82
### ** Java**
72
83
73
84
<!-- 这里可写当前语言的特殊实现逻辑 -->
74
85
75
86
``` java
76
-
87
+ class Solution {
88
+ public int maximumProfit (int [] present , int [] future , int budget ) {
89
+ List<int[]> arr = new ArrayList<> ();
90
+ for (int i = 0 ; i < present. length; ++ i) {
91
+ if (future[i] > present[i]) {
92
+ arr. add(new int []{present[i], future[i] - present[i]});
93
+ }
94
+ }
95
+ int [] dp = new int [budget + 1 ];
96
+ for (int [] e : arr) {
97
+ int v = e[0 ], w = e[1 ];
98
+ for (int j = budget; j >= v; -- j) {
99
+ dp[j] = Math . max(dp[j], dp[j - v] + w);
100
+ }
101
+ }
102
+ return dp[budget];
103
+ }
104
+ }
77
105
```
78
106
79
107
### ** TypeScript**
@@ -98,7 +126,7 @@ class Solution {
98
126
public:
99
127
int maximumProfit(vector<int >& present, vector<int >& future, int budget) {
100
128
int n = present.size();
101
- vector<int >dp(budget + 1, 0 );
129
+ vector<int >dp(budget + 1);
102
130
for (int i = 0; i < n; i++) {
103
131
for (int j = budget; j >= present[ i] ; j--) {
104
132
dp[ j] = max(dp[ j] , dp[ j - present[ i]] + future[ i] - present[ i] );
@@ -109,6 +137,34 @@ public:
109
137
};
110
138
```
111
139
140
+ ### **Go**
141
+
142
+ ```go
143
+ func maximumProfit(present []int, future []int, budget int) int {
144
+ arr := [][]int{}
145
+ for i, v := range present {
146
+ if future[i] > v {
147
+ arr = append(arr, []int{v, future[i] - v})
148
+ }
149
+ }
150
+ dp := make([]int, budget+1)
151
+ for _, e := range arr {
152
+ v, w := e[0], e[1]
153
+ for j := budget; j >= v; j-- {
154
+ dp[j] = max(dp[j], dp[j-v]+w)
155
+ }
156
+ }
157
+ return dp[budget]
158
+ }
159
+
160
+ func max(a, b int) int {
161
+ if a > b {
162
+ return a
163
+ }
164
+ return b
165
+ }
166
+ ```
167
+
112
168
### ** ...**
113
169
114
170
```
0 commit comments