1. 程式人生 > >【leetcode】122.(Easy)Best Time to Buy and Sell Stock II

【leetcode】122.(Easy)Best Time to Buy and Sell Stock II

解題思路:

迭代更新
時間複雜度:O(n)

提交程式碼:滑動視窗

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0)    return 0;
        int res=0,inPrice=prices[0];
    	for(int i=0;i<prices.length;i++) {
        	if(prices[i]<inPrice)
        		inPrice=prices[i];
        	else {
res+=prices[i]-inPrice; inPrice=prices[i]; } } return res; } }

執行結果:
在這裡插入圖片描述