<style> html, body, .ui-content { background: #222222; color: #00BFFF; } /* 設定 code 模板 */ .markdown-body code, .markdown-body tt { background-color: #ffffff36; } .markdown-body .highlight pre, .markdown-body pre { color: #ddd; background-color: #00000036; } .hljs-tag { color: #ddd; } .token.operator { background-color: transparent; } /* 設定連結 */ a, .open-files-container li.selected a { color: #89FFF8; } a:hover, .open-files-container li.selected a:hover { color: #89FFF890; } </style> ###### tags: `Leetcode` # 904. Fruit Into Baskets ###### Link : https://leetcode.com/problems/fruit-into-baskets/submissions/ ## 題目 有兩個籃子,一個籃子只能裝一種水果。 選一顆水果樹開始,後面的每棵樹都要摘一顆水果下來。 計算最多能裝幾個水果。 ## 程式碼 ```cpp= class Solution { public: int totalFruit(vector<int>& fruits) { const int n = fruits.size(); //初始化num1為fruits的第一個水果 num2為-1(不存在) count為1 //num1Index為num1的水果最右邊的位置 num2為num2代表的水果最右邊的位置 int num1 = fruits[0], num2 = -1, cnt = 1, num1Index = 0, num2Index = -1, ans = 1; for(int i = 1;i < n;i++){//迴圈從1開始 //如果目前的水果種類 不屬於num1和num2 if(num1 != fruits[i] && num2 != fruits[i]){ //看哪種水果可以減去較少水果 if(num1Index < num2Index){//不要num1水果 //cnt變成目前位置扣掉num1水果最右邊的位置 cnt = i - num1Index; //num1更新成目前的水果 num1 = fruits[i]; //num1Index變成目前的index num1Index = i; } else{//不要num2水果 //num2原本是-1代表並沒有要扣除水果(原本只有一種,迴圈最開始的情況) if(num2 != -1) cnt = i - num2Index; else ++cnt; //num2更新成目前的水果 num2 = fruits[i]; //num2Index變成目前的index num2Index = i; } } else{//目前的水果不是num1類就是num2類 //更新num1Index或num2Index成目前的index num1 == fruits[i]? (num1Index = i) : (num2Index = i); //count++ ++cnt; } //更新最長的長度 if(ans < cnt) ans = cnt; } return ans; } }; ``` ## Date ### 2023/2/7
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up