Leetcode122 买卖股票的最佳时机 II (c#-数组)

 2019/1/29 再写了一次用了10分钟。其实就是判断后面只要大于前面就减去,将减去的值相加即得到结果。

题目:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

public class Solution {
    public int MaxProfit(int[] prices) {
         int sum = 0;
			for (int i = prices.Length-1; i>0 ; i--)
			{
				if (prices[i]<prices[i-1])
				{
					 
				}
				else
				{
					sum+= prices[i] - prices[i - 1];
				}
			}
			return sum;
    }
}

 执行用时: 156 ms, 在Best Time to Buy and Sell Stock II的C#提交中击败了58.82% 的用户

                                              ---------------------------时间分割线---------------------------

 

[7,1,5,3,6,4]

 第一位  7 :  7>1   过

第二、三位   1 :  1<5   5<3    选5       5-1=4       过

第四位: 3<6   6>4  选6-3=3  过

Are you find the law? Yes,I'm finding,but I can't write . 

        static void Main(string[] args)
        {
            int[] tt = new int[] { 7, 1, 5, 3, 6, 4 };
            int nums = 0, sum = 0;
            for (int i = 0; i < tt.Length-1; i++)
            {
                if (tt[i]>tt[i+1])
                {
                     // 7<1 过  (规律:前一个小于后一个)
                }
                else if (tt[i]>tt[i+1]||tt[i+1]>tt[i+2])    //如果它的下一个大于自己,并且下一个的下一个大于下一个 就符合要求
                {
                    nums = tt[i + 1] - tt[i];
                    sum += nums;
                    nums = 0;
                } 
            }
            Console.WriteLine(sum); 
            Console.ReadKey(); 
        }

只要找到规律,轻轻松松写出来。  此题一遍过.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值