Learn More →
Learn More →
Learn More →
Learn More →
Learn More →
Learn More →
我一直在想怎麼寫DP
結果我後來直接放棄DP
直接刻Greedy
我的想法是
一個subarray如果是負的
那一定是正的subarray乘上負的subarray
而且這題是乘越多越好,
所以我把這題看成三個條件
正的subarray
負的subarray
這三種可能性去取最大值
如果中途遇到0,就當作一個新的array重新計算
這樣的結果會是
class Solution {
public:
int maxProduct(vector<int>& nums) {
long long ma=nums[0];
long long pos=max(0,nums[0]),neg=1;
int i=0, j=0;
while(i<nums.size())
{
long long a=1,neg;
bool flag=1;
for(j=i;j<nums.size();j++,i++)
{
if(nums[j]==0)
{
flag=0;
ma=max(ma,0LL);
break;
}
a*=nums[j];
ma=max(ma,a);
if(nums[j]<0)
{
break;
}
}
neg=min(1LL,a);
if(flag)
{
a=1;
long long tmp=1;
for(j=j+1;j<nums.size();j++,i++)
{
if(nums[j]==0)
{
ma=max(ma,0LL);
break;
}
a*=nums[j];
ma=max(ma,a);
if(nums[j]<0)
{
tmp=1;
}
tmp*=nums[j];
}
if(a<0)
{
ma=max(ma,neg*a);
}
else
{
ma=max(ma,(a/tmp)*neg);
}
}
i++;
}
return ma;
}
};
Learn More →
44分鐘
完全自己解出
好老的梗題
假設有2塊、5塊
初始化先把所有變-1,代表不能放
再把dp[0]設為0,代表能放而且最少需要0個
接著試著放2塊,如果放2塊前是可以達成的,
那就幫他的放2塊後設成(放2塊前的數量+1)
放5塊是同樣的道理,只是過程中不斷取最小值而已(ex:10元會從5被更新成2)
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1,-1);
dp[0]=0;
for(auto coin:coins)
{
for(int i=0;i<=amount-coin;i++)
{
if(dp[i]!=-1)
{
if(dp[i+coin]==-1)
{
dp[i+coin]=dp[i]+1;
}
else
{
dp[i+coin]=min(dp[i+coin],dp[i]+1);
}
}
}
}
return dp[amount];
}
};
7分鐘
完全自己解出
簡單枚舉法
但我沒想到怎麼加速now那個vector的複製
erase也需要一點時間,也許不是最佳的方法
所以花了一點時間想
最後還是決定直接丟過去
class Solution {
public:
void dfs(vector<vector<int>> &ans,vector<int>& nums,vector<int> now,int x)
{
if(x==nums.size())
{
return;
}
dfs(ans,nums,now,x+1);
now.push_back(nums[x]);
ans.push_back(now);
dfs(ans,nums,now,x+1);
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> now;
ans.push_back(now);
dfs(ans,nums,now,0);
return ans;
}
};
10分鐘
完全自己解出
已填
完全自己解出
May 30, 2024留言建議修訂請以 prune and search 解 selection problem。在以下 25 個數字中,要找出第 14 小的數。25 個數字依序為:15,18,12,10,12,4,6,14,10,1,3,5,1,5,20,3,4,10,7,5,1,15,2,4,8。分組方式為:第一組為第 1 到 5 個數字,第二組為第 6 到 10 個,依此類推。(A)請問第一回合找到的 p 值為多少?(B)請問第一回合,被刪去幾個數字?刪去的數字為何?
May 27, 2024image
May 20, 2024\begin{bmatrix} 17 & 13 & 4 & 23 & 12\\ 32 & 30 & 45 & 19 & 31\\ 7 & 11 & 12 & 3 & 15 \\ 10 & 17 & 13 & 9 & 11\\ 8 & 19 & 9 & 6 & 7 \end{bmatrix}
May 10, 2024or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up