You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Solution
Maybe we can’t find the best time to buy the stock, but we know which stock that we shouldn’t buy
This problem is one of the series of 【Buy and Sell Stock】 problems.
In this case, you can buy and sell multiple times.
In our first solution, we Buy The Dip and Sell The Tip
If the price is decreasing, we will wait for the bottom.
In the other case, if the price is increasing, we will wait for the top and sell it.
C# Solution
Solution1
public class Solution {
public int MaxProfit(int[] prices) {
int res = 0;
int buy = 0;
for(int i = 0; i<prices.Length; i++)
{
while(i+1<prices.Length && prices[i]>=prices[i+1])
{
i++;
}
buy = prices[i];
while(i+1<prices.Length && prices[i]<prices[i+1])
{
i++;
}
res += prices[i]-buy;
}
return res;
}
}
Solution2
The second solution is more easy, just check if the next price is higher than now price or not.
If higher, than add the difference of them.
public class Solution {
public int MaxProfit(int[] prices) {
int res = 0;
for(int i = 1; i<prices.Length; i++)
{
if(prices[i]>prices[i-1])
{
res += prices[i]-prices[i-1];
}
}
return res;
}
}
Java Solution
Solution1
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
int buy = 0;
for(int i = 0; i<prices.length; i++)
{
while(i+1<prices.length && prices[i]>=prices[i+1])
{
i++;
}
buy = prices[i];
while(i+1<prices.length && prices[i]<prices[i+1])
{
i++;
}
res += prices[i]-buy;
}
return res;
}
}
Solution2
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 1; i<prices.length; i++)
{
if(prices[i]>prices[i-1])
{
res += prices[i]-prices[i-1];
}
}
return res;
}
}
Python3 Solution
Solution1
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
buy = 0
i = 0
while(i<len(prices)):
###for i in range(0,len(prices)):
while(i+1<len(prices) and prices[i]>=prices[i+1]):
i+=1
print(i)
buy = prices[i]
while(i+1<len(prices) and prices[i]<prices[i+1]):
i+=1
res += (prices[i]-buy)
i+=1
return res
Solution2
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
for i in range(1,len(prices)):
if(prices[i]>prices[i-1]):
res += prices[i]-prices[i-1]
return res
JavaScript Solution
Solution1
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var res = 0;
var buy = 0;
for(let i = 0; i<prices.length; i++)
{
while(i+1<prices.length && prices[i]>=prices[i+1])
{
i++;
}
buy = prices[i];
while(i+1<prices.length && prices[i]<prices[i+1])
{
i++;
}
res += prices[i]-buy;
}
return res;
};
Solution2
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var res = 0;
for(let i = 1; i<prices.length; i++)
{
if(prices[i]>prices[i-1])
{
res += prices[i]-prices[i-1];
}
}
return res;
};
Conclusion
🧡If my solution helps, that is my honor!
✅If you got any problem about the explanation, please feel free to let me know
function returnDefault(item)
{
item.innerText = "Copy"
item.style.color = "white"
item.style.backgroundColor = "CornflowerBlue";
}
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) == false) //20221128 手機用戶移除copy功能
{
jQuery('code').each(function () {
var btn = document.createElement("button");
btn.innerHTML = "Copy";
btn.onmousedown = "event.preventDefault();";
btn.setAttribute('class', 'btnC');
btn.onclick = function(){
var k = this.nextSibling;
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';// Avoid flash of the white box if rendered for any reason.
textArea.style.background = 'transparent';textArea.value = k.textContent;document.body.appendChild(textArea);
textArea.focus();
textArea.select();var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';if(successful)
{
this.focus();
this.style.backgroundColor = "green";
this.innerText = "✔Copied"
openPop();
setTimeout(( ()=>returnDefault(this)),1850)
}document.body.removeChild(textArea);
};var parent = this.parentNode;
parent.insertBefore(btn, this);
});
}
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"02826b5e3c"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"02826b5e3c","uagb_grid_ajax_nonce":"d2ce409c48"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-b2103a3f .uagb-post-pagination-wrap a' );
elements.forEach(function(element) {
element.addEventListener("click", function(event){
event.preventDefault();
const link = event.target.getAttribute('href').match( /\/page\/\d+\// )?.[0] || '';
const regex = /\d+/; // regular expression to match a number at the end of the string
const match = link.match( regex ) ? link.match( regex )[0] : 1; // match the regular expression with the link
const pageNumber = parseInt( match ); // extract the number and parse it to an integer
window.UAGBPostGrid._callAjax({"btnBorderStyle":"none","overallBorderColor":"","block_id":"b2103a3f","categories":"62","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"orderBy":"rand","paddingTop":20,"paddingBottom":20,"paddingRight":20,"paddingLeft":20,"excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"paginationMarkup":"empty","imageRatio":"2-3","imgEqualHeight":true,"btnBorderLink":true,"btnBorderRadiusLink":true,"overallBorderLink":true,"overallBorderRadiusLink":true,"inheritFromTheme":true,"postType":"post","postDisplaytext":"No post found!","taxonomyType":"category","postsToShow":6,"enableOffset":false,"postsOffset":0,"displayPostDate":true,"excerptLength":15,"displayPostAuthor":false,"displayPostTitle":true,"displayPostTaxonomy":false,"hideTaxonomyIcon":true,"taxStyle":"default","displayPostTaxonomyAboveTitle":"withMeta","imgPosition":"top","bgOverlayColor":"#000000","overlayOpacity":"50","displayPostLink":true,"newTab":false,"ctaText":"Read More","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"align":"left","width":"wide","order":"desc","rowGap":20,"rowGapTablet":20,"rowGapMobile":20,"columnGap":20,"bgType":"color","bgColor":"#f6f6f6","titleTag":"h4","titleFontSize":"","titleFontSizeType":"px","titleFontFamily":"","titleLineHeightType":"em","titleLoadGoogleFonts":false,"metaColor":"","highlightedTextColor":"#fff","highlightedTextBgColor":"#3182ce","metaFontSize":"","metaFontSizeType":"px","metaFontFamily":"","metaLineHeightType":"em","metaLoadGoogleFonts":false,"excerptColor":"","excerptFontSize":"","excerptFontSizeType":"px","excerptFontFamily":"","excerptLineHeightType":"em","excerptLoadGoogleFonts":false,"displayPostContentRadio":"excerpt","ctaBgType":"color","ctaBgHType":"color","ctaFontSize":"","ctaFontSizeType":"px","ctaFontFamily":"","ctaLineHeightType":"em","ctaLoadGoogleFonts":false,"contentPadding":20,"ctaBottomSpace":0,"ctaBottomSpaceTablet":0,"ctaBottomSpaceMobile":0,"imageBottomSpace":15,"titleBottomSpace":15,"metaBottomSpace":15,"excerptBottomSpace":25,"contentPaddingUnit":"px","rowGapUnit":"px","columnGapUnit":"px","excerptBottomSpaceUnit":"px","paginationSpacingUnit":"px","imageBottomSpaceUnit":"px","titleBottomSpaceUnit":"px","metaBottomSpaceUnit":"px","ctaBottomSpaceUnit":"px","paddingBtnUnit":"px","mobilePaddingBtnUnit":"px","tabletPaddingBtnUnit":"px","paddingUnit":"px","mobilePaddingUnit":"px","tabletPaddingUnit":"px","isPreview":false,"taxDivider":", ","titleLetterSpacing":"","titleLetterSpacingType":"px","metaLetterSpacing":"","metaLetterSpacingType":"px","ctaLetterSpacing":"","ctaLetterSpacingType":"px","excerptLetterSpacing":"","excerptLetterSpacingType":"px","boxShadowColor":"#00000070","boxShadowHOffset":0,"boxShadowVOffset":0,"boxShadowBlur":"","boxShadowSpread":"","boxShadowPosition":"outset","boxShadowColorHover":"","boxShadowHOffsetHover":0,"boxShadowVOffsetHover":0,"boxShadowBlurHover":"","boxShadowSpreadHover":"","boxShadowPositionHover":"outset","borderWidth":"","borderStyle":"none","borderColor":"","borderRadius":"","blockName":"post-grid","equalHeight":true,"paginationBgActiveColor":"#e4e4e4","paginationActiveColor":"#333333","paginationBgColor":"#e4e4e4","paginationColor":"#777777","paginationLayout":"filled","paginationBorderColor":"#888686","paginationBorderSize":1,"paginationSpacing":20,"paginationAlignment":"left","paginationPrevText":"\u00ab Previous","paginationNextText":"Next \u00bb","layoutConfig":[["uagb\/post-image"],["uagb\/post-taxonomy"],["uagb\/post-title"],["uagb\/post-meta"],["uagb\/post-excerpt"],["uagb\/post-button"]],"post_type":"grid","equalHeightInlineButtons":false}, pageNumber, 'b2103a3f');
});
});
} )();
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};