leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

commit 2231ace554c963cf5592adc6c58a49bd524181c7
parent f3112ac70d2216bb1091ebb4fb3634a87a1efda2
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Tue,  7 Feb 2023 15:34:40 +0100

Daily Problem

Diffstat:
AProblems/0904.cpp | 39+++++++++++++++++++++++++++++++++++++++
MREADME.md | 1+
2 files changed, 40 insertions(+), 0 deletions(-)

diff --git a/Problems/0904.cpp b/Problems/0904.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int totalFruit(vector<int> &fruits) { + pair<int, int> used = {fruits[0], -1}, count = {0, 0}, pos = {0, 0}; + int start = 0, res = 0; + + for (start = 0; start < fruits.size(); start++) + if (fruits[start] != used.first) + break; + else + count.first++; + + if (start == fruits.size()) return count.first; + + used.second = fruits[start]; + for (int i = start; i < fruits.size(); i++) { + if (fruits[i] == used.first) + count.first++, pos.first++, pos.second = 0; + else if (fruits[i] == used.second) + count.second++, pos.first = 0, pos.second++; + else { + res = max(res, count.first + count.second); + if (fruits[i - 1] == used.second) { + used.first = fruits[i]; + count = pos; + pos = {1, 0}; + count.first++; + } else { + used.second = fruits[i]; + count = pos; + pos = {0, 1}; + count.second++; + } + } + } + + return max(res, count.first + count.second); + } +}; diff --git a/README.md b/README.md @@ -273,6 +273,7 @@ for solving problems. | 0886 | Medium | [Possible Bipartition](Problems/0886.cpp) | | 0897 | Easy | [Increasing Order Search Tree](Problems/0897.cpp) | | 0901 | Medium | [Online Stock Span](Problems/0901.cpp) | +| 0904 | Medium | [Fruit Into Baskets](Problems/0904.cpp) | | 0905 | Easy | [Sort Array By Parity](Problems/0905.cpp) | | 0909 | Medium | [Snakes and Ladders](Problems/0909.cpp) | | 0912 | Medium | [Sort an Array](Problems/0912.cpp) |